gpt4 book ai didi

c++ - 哪个版本的 C++ 标准允许重用先前由具有 const 或引用成员的类的对象占用的存储空间?

转载 作者:行者123 更新时间:2023-12-05 04:29:42 25 4
gpt4 key购买 nike

This answer引用了一些未知的 C++ 标准草案修订版:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if:

  • the storage for the new object exactly overlays the storage location which the original object occupied, and

  • the new object is of the same type as the original object (ignoring the top-level cv-qualifiers), and

  • the type of the original object is not const-qualified, and, if a class type, does not contain any non-static data member whose type is const-qualified or a reference type, and

  • neither the original object nor the new object is a potentially-overlapping subobject ([intro.object]).

这意味着如果类 A 具有 const 或引用成员,则以下代码无效:

A a;
a.~A();
new (&a) A;

[basic.life]p8 的当前版本没有这个要求:

If, after the lifetime of an object has ended and before the storage which the object occupied is reused or released, a new object is created at the storage location which the original object occupied, a pointer that pointed to the original object, a reference that referred to the original object, or the name of the original object will automatically refer to the new object and, once the lifetime of the new object has started, can be used to manipulate the new object, if the original object is transparently replaceable (see below) by the new object. An object o1 is transparently replaceable by an object o2 if:

  • the storage that o2 occupies exactly overlays the storage that o1 occupied, and
  • o1 and o2 are of the same type (ignoring the top-level cv-qualifiers), and
  • o1 is not a complete const object, and
  • neither o1 nor o2 is a potentially-overlapping subobject ([intro.object]), and
  • either o1 and o2 are both complete objects, or o1 and o2 are direct subobjects of objects p1 and p2, respectively, and p1 is transparently replaceable by p2.

这使得上面的代码有效。

但这两个引文都来自草稿。所以我不知道从标准的女巫版本开始我可以将上面的代码用于具有 const 或引用成员的类对象。答案日期是2018年5月7日。所以我猜它只能是C++20?

最佳答案

就“主要”标准版本而言,关于 const 资格的条款(您在问题中引用的摘录中强调了这一点)出现在 final draft for the C++17 Standard 中。 (N4659) 但出现在 that for the C++20 Standard 中(N4861).

因此,从中可以看出,符合 C++20(或更高版本)需要重用以前由 const 或包含引用占用的存储空间类对象(在此上下文中)。

关于c++ - 哪个版本的 C++ 标准允许重用先前由具有 const 或引用成员的类的对象占用的存储空间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72250710/

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