gpt4 book ai didi

c++ - 使用 placement new 更新引用成员?

转载 作者:太空狗 更新时间:2023-10-29 19:57:32 25 4
gpt4 key购买 nike

以下代码在 C++ 中是否合法?

template<typename T>
class Foo {
public:
Foo(T& v) : v_(v) {}

private:
T& v_;
};

int a = 10;
Foo<int> f(a);

void Bar(int& a) {
new (&f)Foo<int>(a);
}

引用不应该被绑定(bind)两次,对吧?

最佳答案

这是完全无效的。

[basic.life]/1,强调我的:

The lifetime of an object of type T ends when:

  • if T is a class type with a non-trivial destructor (12.4), the destructor call starts, or
  • the storage which the object occupies is reused or released.

placement new 重用了存储,结束了 f 表示的对象的生命周期。

[basic.life]/7:

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 (1.8) of type T and the new object is a most derived object of type T (that is, they are not base class subobjects).

由于不满足第三个要点,调用Bar后,f不引用placementnew创建的对象>,但对于以前存在的不再存在的对象,并尝试使用它会导致未定义的行为。

另见 CWG1776P0137R0 .

关于c++ - 使用 placement new 更新引用成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33514809/

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