是否为C ++中的类私有成员保证了内存中的顺序? [英] Is order in memory guaranteed for class private members in C++?

查看:100
本文介绍了是否为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?

推荐答案

保证它们彼此之间的地址越来越多( [class.mem] / 13 ):

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


(的非静态数据成员非联盟)具有相同访问权限
控件的类 (条款[class.access]),以便以后的成员
在类对象中具有更高的地址。

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.

请注意我用粗体标记的文本。虽然可以保证 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 ++中的类私有成员保证了内存中的顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆