This is not a duplicate of this question, I read the answers and I still have some questions about this subject.
I tested some classes like this one:
class A {
private:
int b;
public:
char c;
int a;
private:
char e;
};
And I've seen that the fields are stored as if there were no access-specifier, this is not wrong since :
N3376 (the first post C++11 draft) 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).
What I still don't understand is this :
The order of allocation of non-static data members with different access control is unspecified.
What do they mean by unspecified, GCC certainly have a way of doing this, they don't just do it randomly I guess... They don't want the user to know it ? Or there is so many ways depending on the options maybe ?
Because all the examples I tried, I had the same order as declared in my file (+ padding)
I am using gcc 4.9.2, Does anyone know if GCC specified their way of doing this ?
I need to know this because I am creating a program that calculates the padding between all fields, the program works with structures that have no access specifiers for the moment. I will have to find a way to do this when there is different accessibility blocks
By unspecified means the compiler is:
And implementation-defined means, the compiler is free to make any decision, and is required to document it..
If you consider this class (slightly modified your version):
class X {
private:
int b;
int z;
public:
char c;
int a;
private:
char e;
public:
int d;
};
then the text from the spec means:
&c < &a
— both belong to same access control.&b < &z
— both belong to same access control.&z < &e
— both belong to same access control, with interleaving.&a < &d
— both belong to same access control, with interleaving.&z < &c
— both belong to different access control.&a < &e
— both belong to different access control.I've seen code which uses access specifier for each variable, so that the compiler can re-arrange them in order to make the size as smaller as possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With