Search code examples
c++c++14class-members

Is order in memory guaranteed for class private members in C++?


class my_class_t {

private:
    uint64_t field1;
    uint64_t field2;
};

Is order of field1 and field2 guaranteed in memory by C++ Standard?

UPD. Answers said that field2 it is, but &field2 may be not equal to &field1 + 1. How to ensure that field2 will be immediately after field1?


Solution

  • They are guaranteed to have increasing addresses with respect to each other ([class.mem]/13):

    Nonstatic data members of a (non-union) class with the same access control (Clause [class.access]) are allocated so that later members have higher addresses within a class object.

    Note the text I marked in bold. While it's guaranteed field2 is after field1 when they are both private, it need not be the case if they had different access control. And of course, intermediate padding is always an option.

    But if you want to force the absence of padding, and they are of the same type, an array would do it:

    uint64_t field[2];
    

    It also makes &field[0] + 1 well defined, since those objects are now obviously members of the same array.