简体   繁体   English

C++ alignment 多维数组结构

[英]C++ alignment of multidimensional array structure

In my code, I have to consider an array of arrays, where the inner arrays are of a fixed dimension.在我的代码中,我必须考虑一个 arrays 数组,其中内部 arrays 是固定维度的。 In order to make use of STL algorithms, it is useful to actually store the data as array of arrays, but I also need to pass that data to a C library, which takes a flattened C-style array.为了使用 STL 算法,将数据实际存储为 arrays 的数组很有用,但我还需要将该数据传递给 C 库,该库采用扁平化的 C 样式数组。

It would be great to be able to convert (ie flatten) the multi-dimensional array cheaply and in a portable way.如果能够以可移植的方式廉价地转换(即展平)多维数组,那就太好了。 I will stick to a very simple case, the real problem is more general.我会坚持一个非常简单的案例,真正的问题更普遍。

struct my_inner_array { int data[3]; };
std::vector<my_inner_array> x(15);

Is

&(x[0].data[0])

a pointer to a continuous block of memory of size 45*sizeof(int) containing the same entries as x?指向大小为 45*sizeof(int) 的连续块 memory 的指针,其中包含与 x 相同的条目? Or do I have to worry about alignment?还是我必须担心 alignment? I am afraid that this will work for me (at least for certain data types and inner array sizes) but that it is not portable.恐怕这对我有用(至少对于某些数据类型和内部数组大小),但它不可移植。

  1. Is this code portable?此代码可移植吗?
  2. If not, is there a way to make it work?如果没有,有没有办法让它发挥作用?
  3. If not, do you have any suggestions what I could do?如果没有,您对我能做什么有什么建议吗?
  4. Does it change anything at all if my_inner_array is not a POD struct, but contains some methods (as long as the class does not contain any virtual methods)?如果 my_inner_array 不是 POD 结构,但包含一些方法(只要 class 不包含任何虚拟方法),它会改变任何东西吗?

1 Theoretically no. 1 理论上没有。 The compiler may decide to add padding to my_inner_array.编译器可能会决定向 my_inner_array 添加填充。 In practice, I don't see a reason why the compiler would add padding to a struct that has an array in it.实际上,我看不出为什么编译器会向其中包含数组的结构添加填充。 In such a case there's no alignment problem creating an array of such structs.在这种情况下,创建此类结构的数组没有 alignment 问题。 You can use a compile time assert:您可以使用编译时断言:

typedef int my_inner_array_array[3];
BOOST_STATIC_ASSERT(sizeof(my_inner_array) == sizeof(my_inner_array_array));

4 If there are no virtual methods it shouldn't make any difference. 4 如果没有虚拟方法,应该没有任何区别。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM