tags:

views:

154

answers:

4

The C++ standard imposes an ordering on class member variables in memory. It says that the addresses of member variables have to increase in the order of declaration, but only inside one access section. Very specifically, this does not seem to prevent compilers from laying out access sections in an interleaved way. For example:

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

Does the standard allow compilers to lay out the data members in the order i, k, j, n? This would give compilers some (limited) freedom in optimizing object layout without violating the standard.

A: 

I'm seriously not trying to spam. My first question was about the reasons for restricted ordering (the answer, I just learned, is C compatibility). This second question is about how far you can stretch the interpretation of the standard, and I haven't received an answer to it yet. For example: if interleaving is allowed (as it seems to be), this could be a technique for limited layout optimization without violating the standard. That sounds like a useful application.

Sorry if I offended you, I genuinely think these are 2 different questions. I reworded the question above to be less similar to the other one.

Koen Van Damme
+1  A: 

And no, i think he is NOT trying to spam. This is a valid question and quite interesting i think.

Ok now i think compilers can do that. 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).

Johannes Schaub - litb
+1  A: 

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

Koen Van Damme
+2  A: 

I checked out the C++ standard. In section 9.2, paragraph (or clause or whatever) 12, it says "The order of allocation of nonstatic data members separated by an access-specifier is unspecified." "Unspecified" means implementation-dependent behavior that need not be documented.

Therefore, the standard is explicitly saying nothing about the allocation, except that i must precede j and k must precede n. Therefore, a compiler is allowed to allocate in the order i, k, j, n, and nothing about the ordering need be documented.

David Thornley