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

守給你的承諾、 提交于 2019-12-11 15:34:51

问题


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?


回答1:


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.




回答2:


Yes the order is guaranteed.

The address of field1 must be the same as the address of an instance of my_class_t. field2 has a "higher" address than field1 insofar that positive pointer arithmetic on an unsigned char* pointer obtained by a reinterpret_cast on the address of field1 will eventually reach the memory occupied by field2.

But note that the behaviour on attempting to "reach" field2 by pointer arithmetic on a pointer to field1 is undefined.

As for ensuring there is no padding between the members, you can't do that in portable C++. But you could use an array type:

class my_class_t {
private:
    uint64_t fields[2];
};

which would guarantee that. And then you can reach the members using pointer arithmetic.




回答3:


The order of objects in memory will be same as the order of declaration when access qualifier does not intervene.



来源:https://stackoverflow.com/questions/47592782/is-order-in-memory-guaranteed-for-class-private-members-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!