当前标准草案在 [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 的逻辑后果,因为此类对象会:
- 有初始化,不会开始活,因为没有执行。
- 被默认初始化但没有初始化。我知道这可能会造成混淆。
用目前的措辞,这很清楚。也许某些地方可以明确说明哪些对象进行了初始化,或者进行初始化意味着什么。我想都可以,但我手头没有它的密码。
关于c++ - 对于非空初始化,lifetime starts before initialization 解决了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164295/