Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Layout restriction on a non-standard layout class

Tags:

c++

c++11

Is the compiler free to reorder data in a non-standard layout class? For example, is it allowed to change

struct
{
    char x;
private:
    short y;
public:
    char z;
};

to

struct
{
private:
    short y;
public:
    char x;
    char z;
};
like image 312
a.lasram Avatar asked Jun 28 '13 19:06

a.lasram


1 Answers

EDIT: I misremembered the quote originally, the compiler is allowed to do that per 9.2/14:

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 (11). 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 it can't do is reorder attributes with the same access specifier.

That said I don't know of any implementation that takes the liberty to reorder attributes even across access specifiers.

like image 139
Mark B Avatar answered Oct 19 '22 04:10

Mark B