将double数组转换为double的结构 [英] Casting double array to a struct of doubles
问题描述
可以将双精度数组强制转换为由双精度组成的结构吗?
Is it OK to cast a double array to a struct made of doubles?
struct A
{
double x;
double y;
double z;
};
int main (int argc , char ** argv)
{
double arr[3] = {1.0,2.0,3.0};
A* a = static_cast<A*>(static_cast<void*>(arr));
std::cout << a->x << " " << a->y << " " << a->z << "\n";
}
这将打印1 2 3
.但是是否可以保证每次都可以与任何编译器一起工作?
This prints 1 2 3
. But is it guaranteed to work every time with any compiler?
根据
9.2.21:指向标准布局结构对象的指针,已适当转换?使用reinterpret_cast指向其初始成员(...),反之亦然.
9.2.21: A pointer to a standard-layout struct object, suitably converted ? using a reinterpret_cast, points to its initial member (...) and vice versa.
如果我将代码替换为
struct A
{
double & x() { return data[0]; }
double & y() { return data[1]; }
double & z() { return data[2]; }
private:
double data[3];
};
int main (int, char **)
{
double arr[3] = {1.0,2.0,3.0};
A* a = reinterpret_cast<A*>(arr);
std::cout << a->x() << " " << a->y() << " " << a->z() << "\n";
}
然后保证它可以工作.正确的?我知道很多人不会觉得这令人愉悦,但是使用结构而不需要复制输入数组数据有很多好处.我可以在该结构中定义成员函数,以计算标量和向量乘积,距离等,这将使我的代码比使用数组更容易理解.
then it is guaranteed to work. Correct? I understand that many people would not find this aesteticaly pleasing but there are advantages in working with a struct and not having to copy the input array data. I can define member functions in that struct to compute scalar and vector products, distances etc, that will make my code much easier to understand than if I work with arrays.
怎么样
int main (int, char **)
{
double arr[6] = {1.0,2.0,3.0,4.0,5.0,6.0};
A* a = reinterpret_cast<A*>(arr);
std::cout << a[0].x() << " " << a[0].y() << " " << a[0].z() << "\n";
std::cout << a[1].x() << " " << a[1].y() << " " << a[1].z() << "\n";
}
这是否还可以保证正常工作,或者编译器可以在数据成员之后放置一些内容,以便sizeof(A) > 3*sizeof(double)
?有没有可移植的方法来阻止编译器这样做?
Is this also guaranteed to work or the compiler could put something AFTER the data members so that sizeof(A) > 3*sizeof(double)
? And is there any portable way to prevent the compiler from doing so?
推荐答案
不,不能保证.
唯一常识是禁止任何编译器在x
和y
之间或在y
和z
之间插入填充.任何语言标准中都没有禁止它的规则.
The only thing prohibiting any compiler from inserting padding between x
and y
, or between y
and z
is common sense. There is no rule in any language standard that would disallow it.
即使没有填充,即使A
的表示形式与double[3]
的表示形式完全相同,也仍然无效.该语言不允许您假装一种类型确实是另一种类型.甚至不允许您将struct A { int i; };
的实例视为struct B { int i; };
.
Even if there is no padding, even if the representation of A
is exactly the same as that of double[3]
, then it's still not valid. The language doesn't allow you to pretend one type is really another type. You're not even allowed to treat an instance of struct A { int i; };
as if it's a struct B { int i; };
.
这篇关于将double数组转换为double的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!