c++ - 对于非空初始化,lifetime starts before initialization 解决了什么问题?

标签 c++ initialization language-lawyer c++17 lifetime

当前标准草案在 [basic.life/1] 中说(以前的标准有类似的措辞) :

The lifetime of an object or reference is a runtime property of the object or reference. An object is said to have non-vacuous initialization if it is of a class or aggregate type and it or one of its subobjects is initialized by a constructor other than a trivial default constructor. [ Note: Initialization by a trivial copy/move constructor is non-vacuous initialization. — end note ] The lifetime of an object of type T begins when:

(1.1) storage with the proper alignment and size for type T is obtained, and

(1.2) if the object has non-vacuous initialization, its initialization is complete

为什么这里很重要,初始化是非无意义的?换句话说,如果初始化不是非空,为什么生命周期在初始化完成之前就开始了?它解决了什么问题?

如果 (1.2) 读作会产生什么后果

(1.2) if the object has initialization, its initialization is complete

non-vacuous 这个词只用在这里,肯定有它的道理。


注意,我之前有一个类似的问题here ,但由于这个问题有点过于宽泛(甚至我接受了其中一个答案),那里的回答没有回答当前的问题。

最佳答案

我认为这是为了绕过不执行初始化的默认初始化:

[dlc.init]:

To default-initialize an object of type T means:

(7.1) — If T is a (possibly cv-qualified) class type (Clause 12), constructors are considered. The applicable constructors are enumerated (16.3.1.3), and the best one for the initializer () is chosen through overload resolution (16.3). The constructor thus selected is called, with an empty argument list, to initialize the object.

(7.2) — If T is an array type, each element is default-initialized.

(7.3) — Otherwise, no initialization is performed.

我理解所有的对象都有初始化,但是对于一些默认初始化的对象没有进行初始化。请注意,它明确表示“未执行初始化”,而不是它不存在。

您可以有一个默认初始化的对象,但没有对其执行初始化,因此它无法完成。他们不会开始他们的生命时间,并且按照目前的措辞,他们不必等待这个 no-init 发生来开始他们的生活。此外,此类对象必须进行初始化,因为它是默认初始化的。

恕我直言,您的措辞会有缺陷,或者您的理解会导致默认初始化定义 7.3 的逻辑后果,因为此类对象会:

  1. 有初始化,不会开始活,因为没有执行。
  2. 被默认初始化但没有初始化。我知道这可能会造成混淆。

用目前的措辞,这很清楚。也许某些地方可以明确说明哪些对象进行了初始化,或者进行初始化意味着什么。我想都可以,但我手头没有它的密码。

关于c++ - 对于非空初始化,lifetime starts before initialization 解决了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164295/

相关文章:

c++ - 使用 std::cout 的参数评估顺序

c++ - 检查回调是否由 C++ 中的客户端设置

c++ - Boost.Regex 与 C++11 正则表达式

c++ - 在初始化中使用新声明的变量(int x = x+1)?

c++ - 生成保证顺序执行吗?

c++ - C++ 中 CV 限定的基类

c++ - 从字符串中删除一个字符

c++ - 测试字符串是否代表 "yyyy-mm-dd"

java - 我的 if-else 语句有一个问题,我的变量没有被初始化

c++ - 类型名称后的括号是否与 new 有所不同?