Can C ++ access sections be interleaved?

The C ++ standard imposes ordering on the member variables of a class in memory. It says that the addresses of member variables should increase in the order of declaration, but only within one access section. In particular, this does not appear to prevent compilers from allocating access sections in an alternating fashion. For example:

class X {
public:
   int i;
   int j;
private:
   int k;
   int n;
}

      

Does the standard allow compilers to list items in the order i, k, j, n? This would give compilers some (limited) freedom to optimize the object's layout without breaking the standard.

+1


source to share


3 answers


I have checked the C ++ standard. Paragraph 9.2, paragraph (or section, or whatever) 12 says: "The order of distribution of non-static data items separated by an access specifier is not specified." "Unspecified" means implementation specific behavior that does not need to be documented.



So the standard does not explicitly say anything about allocation, except that I must precede j and k must precede n. Therefore, the compiler is allowed to allocate in the order i, k, j, n, and nothing about the need for ordering needs to be documented.

+3


source


And no, I think he is NOT trying to spam. This is a valid question and a pretty interesting one I think.

Ok now I think compilers can do this. The standard says in 9.2. p12:



Implementation alignment require- ments 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).

+2


source


As I interpret the standard, it sees the example code as follows: since there is no access specifier between i and j, the address i must be before the address j. The proposed ordering satisfies this. The same is for k and n. Therefore, in my interpretation, compilers are allowed to use this order.

+1


source







All Articles