在构造变量之前引用变量是否定义明确
Is it well defined to reference a variable before it's constructed
这与针对 c
提出并回答的 question 在本质上是相似的。那里的评论暗示 c++
的精确答案会有所不同,因此这里有一个针对 c++
.
中编写的代码的类似问题
下面的程序定义的好吗?
int f(int& b)
{
b = 42;
return b;
}
int a { f(a) };
这对我来说似乎没问题,但另一方面,a
是如何根据函数计算的值构造的,该函数本身会修改 a
?我对此有先有鸡还是先有蛋的感觉,所以最好有一个解释。对于它的价值,它 appears 可以工作。
这好像是同一个问题,就这样吧; class 类型和基本类型的答案会有所不同吗?即以下格式是否正确?
struct S { int i; };
S f(S& b)
{
b.i = 42;
return b;
}
S a { f(a) };
再次强调,这个 appears 也能发挥作用。
此行为似乎未在 C++20 中定义。更改由 P1358 解决 CWG 2256。由于缺陷解决方案通常具有追溯性,因此在所有 C++ 版本中应将此代码视为 UB。
... The lifetime of an object of type T
begins when:
- storage with the proper alignment and size for type
T
is obtained, and
- its initialization (if any) is complete (including vacuous initialization) ...
在调用 f(a)
时,对象 a
尚未开始其生命周期,因为其初始化尚未完成。根据 [basic.life]/7:
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated ... any glvalue that refers to the original object may be used but only in limited ways. ... The program has undefined behavior if:
- the glvalue is used to access the object ...
因此,在初始化完成之前写入 a
是 UB,即使存储已经分配。
这与针对 c
提出并回答的 question 在本质上是相似的。那里的评论暗示 c++
的精确答案会有所不同,因此这里有一个针对 c++
.
下面的程序定义的好吗?
int f(int& b)
{
b = 42;
return b;
}
int a { f(a) };
这对我来说似乎没问题,但另一方面,a
是如何根据函数计算的值构造的,该函数本身会修改 a
?我对此有先有鸡还是先有蛋的感觉,所以最好有一个解释。对于它的价值,它 appears 可以工作。
这好像是同一个问题,就这样吧; class 类型和基本类型的答案会有所不同吗?即以下格式是否正确?
struct S { int i; };
S f(S& b)
{
b.i = 42;
return b;
}
S a { f(a) };
再次强调,这个 appears 也能发挥作用。
此行为似乎未在 C++20 中定义。更改由 P1358 解决 CWG 2256。由于缺陷解决方案通常具有追溯性,因此在所有 C++ 版本中应将此代码视为 UB。
... The lifetime of an object of type
T
begins when:
- storage with the proper alignment and size for type
T
is obtained, and- its initialization (if any) is complete (including vacuous initialization) ...
在调用 f(a)
时,对象 a
尚未开始其生命周期,因为其初始化尚未完成。根据 [basic.life]/7:
Similarly, before the lifetime of an object has started but after the storage which the object will occupy has been allocated ... any glvalue that refers to the original object may be used but only in limited ways. ... The program has undefined behavior if:
- the glvalue is used to access the object ...
因此,在初始化完成之前写入 a
是 UB,即使存储已经分配。