Koen Van Damme
Koen Van Damme

Reputation: 400

Can C++ access sections be interleaved?

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.

Upvotes: 1

Views: 293

Answers (3)

David Thornley
David Thornley

Reputation: 57046

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.

Upvotes: 3

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 507115

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

Upvotes: 2

Koen Van Damme
Koen Van Damme

Reputation: 400

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.

Upvotes: 1

Related Questions