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/