本文介绍了是否为C ++中的类私有成员保证了内存中的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class my_class_t {

private:
    uint64_t field1;
    uint64_t field2;
};

field1 和<$ c的顺序$ c> field2 是否通过C ++标准在内存中得到保证?

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

UPD。回答说是 field2 ,但是& field2 可能不等于& field1 + 1 。如何确保 field2 将紧接在 field1 之后?

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?

推荐答案

保证它们彼此之间的地址越来越多():

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

请注意我用粗体标记的文本。虽然可以保证 field2 都在 field1 之后,但它们都是私有的,但如果它们具有不同的访问权限,则不必如此控制。当然,中间填充始终是一个选择。

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];

这还会使& field [0] + 1 定义明确,因为这些对象现在显然是同一数组的成员。

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

这篇关于是否为C ++中的类私有成员保证了内存中的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 23:52