gpt4 book ai didi

c++ - 非结构对象布局

转载 作者:行者123 更新时间:2023-11-28 05:23:33 25 4
gpt4 key购买 nike

我一直在阅读 Lippman 的“Inside the C++ Object Model”我遇到了以下事情:

The data members within a single access section are guaranteed within C++ to be laid out in the order of their declaration. The layout of data contained in multiple access sections, however, is left undefined.

下面代码中的注释是否正确?

class Foo
{
public:
Foo(): a_(1), b_(2), c_(3)
{
// it does not matter that the order of a_, b_, c_ is the same in class definition and in initialization list, we do not know which one will be initialized first?
}

public:
int a_;

private:
int b_;

protected:
int c_;
};

如果是这样,那么包含成员组的几个私有(private)部分呢?

class Foo
{
public:
Foo(): a_(1), b_(2)
{
// is initialization order guaranteed?
}

private:
int a_;

private:
int b_;
};

此外,也许我可以在标准中阅读有关它的任何内容?

UPD

当我有:

class Foo
{
public:
Foo(): a_(1), b_(2) {}
private:
int a_;
int b_;
};

我确定一切正常:a_ 在 b_ 初始化之前初始化。

当我有:

class Foo
{
public:
Foo(): a_(1), b_(2) {}
public:
int a_;
private:
int b_;
};

据我所知,我无法确定 a_ 在 b_ 初始化之前就已初始化。

为什么?因为,正如我们所知,初始化顺序仅由声明顺序强烈决定。但是在上面的引述中说,a_(作为公共(public))和 b_(作为私有(private))的声明顺序是未指定的。

最佳答案

布局:

如您引用的文本所述,布局取决于声明顺序和访问控制。分配具有相同访问控制的所有成员,以便后来声明的成员在对象中具有更高的权限。具有不同访问控制的成员的顺序未指定。请注意,这允许根据声明顺序布置所有成员。

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 (Clause 11).

N4296 §9.2/13

.

初始化

初始化按照成员声明的顺序进行,成员初始化器的顺序(构造函数的 : 之后的顺序)无关紧要:

Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

N4296 §12.6.2/13.3

访问控制无关紧要。

实证验证

#include <iostream>
using std::cout;
using std::endl;

struct A
{
A()
{
cout << "A" << endl;
}
};

struct B
{
B()
{
cout << "B" << endl;
}
};

struct X
{
A a;
B b;
X() : b(), a() {}
};

int main() {
X x;
cout << "a @ " << &(x.a) << endl;
cout << "b @ " << &(x.b) << endl;
return 0;
}

将输出 ( live on ideone )

A
B
some_address
some_address + 1

处理您的编辑:

class Foo
{
public:
Foo(): a_(1), b_(2) {}
public:
int a_;
private:
int b_;
};

As I understand, I cannot be sure that a_ is initialized before b_ is initialized.

是的,你可以确定 a_b_ 之前被初始化。这是由标准保证的。

But in the quoute above is said, that the order of declaration of a_ (as public) and b_ (as private) is unspecified.

引用说 a_b_ 在内存中的(相对)布局未指定。这与初始化顺序无关。

关于c++ - 非结构对象布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40991729/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com