为结构成员分配的内存是否连续?如果结构成员是数组怎么办? [英] Is the memory allocated for struct members continguous? What if a struct member is an array?

查看:79
本文介绍了为结构成员分配的内存是否连续?如果结构成员是数组怎么办?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设在C/C ++中,我定义了一个名为test的简单结构,如下所示.

In C/C++ suppose I define a simple struct named test as follows.

struct test
{
   double height;
   int    age;
   char   gender;
}

对于此结构的特定实例,请说test AA.height, A.age, A.gender连续的 在记忆中?

For a specific instance of this struct say test A are A.height, A.age, A.gender contiguous in memory?

更一般地说,数组的结构和结构的数组在内存中的布局看起来如何?图片真的很有帮助.

More generally, how do the layouts in memory for a Structure of Arrays and an Array of structures look like? A picture would be really helpful.

推荐答案

它们在内存中不一定是连续的.这是由于结构填充.

They will not necessarily be contiguous in memory. This is due to struct padding.

但是,在您的特定情况下,它很可能是连续的.但是,如果您将顺序更改为以下形式:

However, in your particular case, it may very well be contiguous. But if you changed the order to something like this:

struct test
{
    char   gender;
    int    age;
    double height;
}

那么它们很可能不会.但是,在您的特定情况下,您仍可能在gender之后填充,以将结构重新对齐为8个字节.

then they most likely will not be. However, in your particular case, you will still likely get padding after gender, to realign the struct to 8 bytes.

SoA(数组结构)和AoS(结构数组)之间的区别如下:

The difference between SoA (Struct of Arrays) and AoS (Array of Structs) would be like this:

SoA:

-----------------------------------------------------------------------------------
| double | double | double | *pad* | int | int | int | *pad* | char | char | char |
-----------------------------------------------------------------------------------

AoS:

-----------------------------------------------------------------------------------
| double | int | char | *pad* | double | int | char | *pad* | double | int | char |
-----------------------------------------------------------------------------------

请注意,每个结构内都装有AoS垫.当SoA在阵列之间填充时.

Note that AoS pads within each struct. While SoA pads between the arrays.

这些要进行以下权衡:

    由于每个对象"都在一起,
  1. AoS 往往对程序员更具可读性.
  2. 如果同时访问结构的所有成员,则
  3. AoS 可能具有更好的缓存位置.
  4. SoA 可能会更有效率,因为将相同数据类型组合在一起有时会暴露矢量化.
  5. 在许多情况下, SoA 使用的内存更少,因为填充仅在数组之间,而不是在每个结构之间.
  1. AoS tends to be more readable to the programmer as each "object" is kept together.
  2. AoS may have better cache locality if all the members of the struct are accessed together.
  3. SoA could potentially be more efficient since grouping same datatypes together sometimes exposes vectorization.
  4. In many cases SoA uses less memory because padding is only between arrays rather than between every struct.

这篇关于为结构成员分配的内存是否连续?如果结构成员是数组怎么办?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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