C++11 子对象对齐

标签 c++ c++11 memory-alignment

C+11 [basic.align] 说:

An object type imposes an alignment requirement on every object of that type; stricter alignment can be requested using the alignment specifier

紧接着举个例子:

struct B { long double d; };
struct D : virtual B { char c; }

并说明示例的以下内容:

When D is the type of a complete object, it will have a subobject of type B, so it must be aligned appropriately for a long double. If D appears as a subobject of another object that also has B as a virtual base class, the B subobject might be part of a different subobject, reducing the alignment requirements on the D subobject.

那么对对象类型为 D 的所有对象施加的对齐要求是什么?我理解 D 子对象具有对象类型 D,这将使其符契约(Contract)样的要求。当 D 应用于所有子对象时,D 作为子对象的出现如何消除这些要求?或者我应该理解为完整的D对象对对象类型强加的要求有进一步的要求,当D作为子对象出现时,这些要求可能会被削弱?

最佳答案

这是因为D 使用虚拟继承B 派生而来。这意味着如果您定义另一个对象类型,派生自 D 以及 B(同样是虚拟的),

struct E : D , virtual B
{ /*...*/ };

那么 B 子对象将在 E 对象中出现 仅一次,而不是两次。因此,E 对象的 D 子对象可能不包含 B 子对象,因此享有宽松的对齐要求。 (E 对象作为一个整体仍然需要完全对齐。)

关于C++11 子对象对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876606/

相关文章:

windows - 如何在 x64 上为我的进程启用对齐异常?

c++ - 显示正交的 OpenGL 投影矩阵

c++ - C++结构语法 "a : b"是什么意思

c++ - 正确对齐内存中模板,参数顺序不变

gcc - 将 C 函数对齐到 "odd"地址

c++ - 是否可以这样编码 :while(lambda){}

c++ - boost::weak_ptr 与自定义删除器的交互

linux下c++编译错误

c++ - 使用 C++11 创建唯一类型 ID

c++ - 为什么此模板参数推断失败?