Besides accessibility, what else access-specifiers effects?

泪湿孤枕 提交于 2019-12-05 04:29:57
Nawaz

Apart from the accessibility of members outside or to the derived classes, access specifiers might affect the object layout.

Quoting from my other answer:

Usually, memory address for data members increases in the order they're defined in the class . But this order may be disrupted at any place where the access-specifiers (private, protected, public) are encountered. This has been discussed in great detail in Inside the C++ Object Model by Lippman.

An excerpt from C/C++ Users Journal,

The compiler isn't allowed to do this rearrangement itself, though. The standard requires that all data that's in the same public:, protected:, or private: must be laid out in that order by the compiler. If you intersperse your data with access specifiers, though, the compiler is allowed to rearrange the access-specifier-delimited blocks of data to improve the layout, which is why some people like putting an access specifier in front of every data member.

Interesting, isn't it?

From n3225, 9.2 [class.mem] note 15

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 (11).

This means that given the following declaration:

class Foo {
public:  int a;
private: int b;
public:  int c;
private: int d;
};

Only the following assertions are enforced by the standard:

Foo foo;

assert(&foo.a < &foo.c);
assert(&foo.b < &foo.d);

@Nawaz's citation can be interpreted as giving 4 blocks that can be freely intermixed, but this is not the case. The declaration of Foo is perfectly equivalent to:

class Foo' {
public:  int a,c;
private: int b,d;
};

Indeed the compiler completely ignores (for this purpose) whether a specifier appeared once or multiple times, and specifying it each time is spurious and at best slows the compilation down because of the extra parsing. For a human reader, it might be clearer... but this is highly subjective.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!