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

标签 c++ c++11 inheritance standards memory-address

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

最佳答案

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

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

第 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.

当所有 union 成员都是以相同类型序列开始的结构时,有几个关于 union 的句子。然后允许“检查公共(public)部分”,从中可以推断出它们必须具有相同的地址。

终于,我在 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.

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

不幸的是,您甚至不能详细说明基类子对象及其派生对象的地址:也可能存在多重继承。因此该标准不使用地址假设:它宁愿这样表述:“如果基类可访问,则可以将指向派生类的指针隐式转换为指向该基类的指针”

关于关于继承成员地址的 C++ 标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28438245/

相关文章:

c++ - 在 nVidia Optimus 中以编程方式选择集成显卡

c++ - 如何保证接受无限数量参数的函数的类型安全?

c++ - 如何使这些 C++ 类声明起作用

c++ - 从 C++ 中与 C 灵活数组成员互操作的正确方法是什么?

c++ - MT4 DLL/TA-LIB 链接器错误

c++ - 公共(public)访问声明不影响成员函数指针?

c++ - 如何在 llvm 中创建命名局部变量?

c++ - 通过 (Args&&...) 构造一个 std::thread

java - Print Writer 和继承

c# - 如何在实际类中引用枚举而不是 C# 中的基类