gpt4 book ai didi

c++ - 使用 const 成员放置 new 和类的赋值

转载 作者:可可西里 更新时间:2023-11-01 15:48:23 29 4
gpt4 key购买 nike

为什么是未定义的行为?

struct s
{
const int id; // <-- const member

s(int id):
id(id)
{}

s& operator =(const s& m) {
return *new(this) s(m); // <-- undefined behavior?
}
};

(引用标准会很好)。

这个问题来自this answer .

最佳答案

显示的代码片段没有任何内在的 UB。但是,几乎可以肯定,在任何正常使用情况下,UB 都会立即出现。

来自 [basic.life]/8 (强调我的)

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

  • the original object was a most derived object of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).

由于s中有一个const成员,调用operator=后使用原来的变量就是UB。

s var{42};
var = s{420}; // OK
do_something(var.id); // UB! Reuses s through original name
do_something(std::launder(&var)->id); // OK, this is what launder is used for

关于c++ - 使用 const 成员放置 new 和类的赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47473621/

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