我知道显式调用析构函数会导致未定义的行为,因为双重析构函数调用,就像下面这样:
#include <vector>
int main() {
std::vector<int> foo(10);
foo.~vector<int>();
return 0; // Oops, destructor will be called again on return, double-free.
}
但是,如果我们调用placement new来“复活”对象呢?
#include <vector>
int main() {
std::vector<int> foo(10);
foo.~vector<int>();
new (&foo) std::vector<int>(5);
return 0;
}
更正式地说:
new
分配的),然后,在这个对象被析构之前,对它调用placement new来“恢复”它?示例用例(尽管这个问题更多的是关于好奇心):我想“重新分配”一个没有operator=
的对象。
我见过this members,它说“覆盖”具有非静态const
成员的对象是非法的。因此,让我们将这个问题的范围限制在没有任何const
成员的对象上。
https://stackoverflow.com/questions/42598915
复制相似问题