Memory Allocation for Public and Private Fields - GCC Method

This is not a duplicate of this question , I have read the answers, and I still have some questions on this.

I tested several classes like this:

class A { private: int b; public: char c; int a; private: char e; }; 

And I saw that the fields are stored as if there was no access specifier, this is not so, because:

N3376 (first C ++ 11 article) 9.2 [class.mem] / 13:

Non-stationary data members of a (non-unitary) class with the same access control (section 11) are allocated in such a way that later members have higher addresses in the class object. The distribution order of non-static data elements with different access control is not defined. Implementation alignment requirements may result in two adjacent elements not being immediately distributed one after another; therefore, space may be required to manage virtual functions (10.3) and virtual base classes (10.1).

What I still do not understand is:

The distribution order of non-static data elements with different access control is not defined.

What do they mean by unspecified, GCC, of ​​course, has a way to do this, they don’t just do it randomly, I think ... They don’t want the user to know this? Or are there many ways depending on the options?

Since all the examples I tried, I had the same order as in my file (+ addition)

I am using gcc 4.9.2. Does anyone know if the GCC has indicated its way to do this?

I need to know this because I am creating a program that calculates the filling between all fields, the program works with structures that currently do not have access specifiers. I will need to find a way to do this when there are various accessibility blocks

+5
source share
1 answer

Unspecified means that the compiler:

  • freely make any decision he likes
  • and not required for documentation.

And the means defined by the implementation, the compiler can make any decision and must document it.


If you are considering 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 spec means:

  • It is guaranteed that
    • &c < &a - both refer to the same access control.
    • &b < &z - both refer to the same access control.
  • It is also guaranteed that
    • &z < &e - both refer to the same interleaved access control.
    • &a < &d - both refer to the same interleaved access control.
  • it is not guaranteed that:
    • &z < &c - both refer to different access controls.
    • &a < &e - both refer to different access controls.

I saw code that uses an access specifier for each variable, so the compiler can reorder them to make the size as small as possible.

+3
source

All Articles