gpt4 book ai didi

c++ - 了解类对象构造

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:50:58 25 4
gpt4 key购买 nike

我正在阅读 N3797 的第 12.7 条。给出以下示例:

struct X { int i; };
struct Y : X { Y(); }; // non-trivial
struct A { int a; };
struct B : public A { int j; Y y; }; // non-trivial

extern B bobj;
B* pb = &bobj; //1
int* p1 = &bobj.a; //2 undefined, refers to base class member
int* p2 = &bobj.y.i; //3 undefined, refers to member’s member
A* pa = &bobj;
B bobj;
extern X xobj;
int* p3 = &xobj.i;
X xobj;

这个例子必须反射(reflect)规则:

For an object with a non-trivial constructor, referring to any non-static member or base class of the object before the constructor begins execution results in undefined behavior.

但我有一个疑问。如果实现不以静态方式对//1//2//3 执行动态初始化,我们有//2//3 没有未定义的行为,因为 (3.6.2/1):

Constant initialization is performed:

[...]

— if an object with static or thread storage duration is initialized by a constructor call, and if the initialization full-expression is a constant initializer for the object;

[...]

Together, zero-initialization and constant initialization are called static initialization; all other initialization is dynamic initialization. Static initialization shall be performed before any dynamic initialization takes place.

也就是说,我们在非静态和基类之前调用​​了构造函数。所以该示例的结果是实现定义的。

我的推理是否正确?

最佳答案

“它也可能调用 constexpr 构造函数”,Y::Y() 不是 constexpr 构造函数,因此 B bobj 属于动态初始化。

关于c++ - 了解类对象构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25470791/

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