关于继承成员地址的 C++ 标准

C++ Standard On The Address of Inherited Members

C++ 标准对继承成员的地址有说明吗?例如,如果我继承了一个 int 成员或一个非虚拟方法,它是否说明了它的地址或虚拟成员:如果我不覆盖它,如果我覆盖它?构造函数,如果我使用以前的构造函数?运算符、重载运算符、模板成员?它有没有提到这些事情?

标准,1.8节是关于C++对象模型的。

没什么好说的:对象是一个内存区域(但它可能包含用于对齐目的的未使用区域)并且可以包含子对象(成员子对象或基class 子对象,或数组子对象)。从 完整对象的定义 可以推断出子对象包含在其对象的内存区域中。它说两个既不是位域也不是基础 class 子对象的不同对象应具有不同的地址。

第 9.2/15 节提供了有关对象内地址顺序的一些附加信息:

Nonstatic data members of a (non-union) class with the same access control are allocated so that later members have higher addresses within a class object. The order of allocation of non-static data members with different access control is unspecified. Implementation alignment requirements might cause two adjacent members not to be allocated immediately after each other; so might requirements for space for managing virtual functions and virtual base classes.

当所有联合成员都是以相同类型序列开始的结构时,有几个关于联合的句子。然后允许"inspect the common parts",从中可以推断出它们必须具有相同的地址。

终于,我找到了 9.2/21 中的最后一个:

A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.

基本上就是这样。你看到这里有很多实现定义的东西,关于每个对象的确切布局。

不幸的是,您甚至不能详细说明基 class 子对象及其派生对象的地址:也可能存在多重继承。所以该标准不使用地址假设:它宁愿声明如下:"If a base class is accessible, one can implicitly convert a pointer to a derived class to a pointer to that base class"