这不是这个的拷贝 question , 我阅读了答案,但我对这个主题仍有一些疑问。
我测试了一些这样的类:
class A {
private:
int b;
public:
char c;
int a;
private:
char e;
};
而且我已经看到字段的存储方式就好像没有访问说明符一样, 这并没有错,因为:
N3376 (第一篇 C++11 草案)9.2 [class.mem]/13:
Nonstatic data members of a (non-union) class with the same access control (Clause 11) 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 (10.3) and virtual base classes (10.1).
我仍然不明白的是:
The order of allocation of non-static data members with different access control is unspecified.
他们所说的未指定是什么意思,GCC 当然有办法做到这一点,我猜他们不只是随机地做……他们不想让用户知道吗? 或者可能有很多方法取决于选项?
因为我尝试了所有示例,所以我的顺序与文件中声明的顺序相同(+ 填充)
我正在使用 gcc 4.9.2,有谁知道 GCC 是否指定了他们这样做的方式?
我需要知道这一点,因为我正在创建一个程序来计算所有字段之间的填充,该程序使用目前没有访问说明符的结构。当存在不同的可访问性 block 时,我将不得不找到一种方法来执行此操作
最佳答案
未指定 表示编译器是:
- 自由做出任何决定
- 并且不需要记录它。
实现定义意味着编译器可以自由做出任何决定,并且需要记录下来。。
如果你考虑这个类(稍微修改你的版本):
class X {
private:
int b;
int z;
public:
char c;
int a;
private:
char e;
public:
int d;
};
然后规范中的文本意味着:
- 保证
-
&c < &a
— 都属于相同的访问控制。 -
&b < &z
— 都属于相同的访问控制。
-
- 同时保证
-
&z < &e
— 都属于相同的访问控制,具有交错。 -
&a < &d
— 都属于相同的访问控制,具有交错。
-
- 不保证:
-
&z < &c
— 两者属于不同的访问控制。 -
&a < &e
— 两者属于不同的访问控制。
-
我见过为每个变量使用访问说明符的代码,以便编译器可以重新排列它们,以使大小尽可能小。
关于c++ - 公共(public)和私有(private)领域的内存分配 - GCC方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29841973/