将双精度数组转换为双精度结构 [英] Casting double array to a struct of doubles

查看:39
本文介绍了将双精度数组转换为双精度结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将双精度数组转换为双精度结构吗?

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?

推荐答案

不,不能保证.

唯一禁止任何编译器在 xy 之间或 yz 之间插入填充的东西是常识.任何语言标准中都没有禁止它的规则.

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; };.

这篇关于将双精度数组转换为双精度结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆