有时候重新开始是件好事。在 C++ 中,我可以采用以下简单操作:
{
T x(31, Blue, false);
x.~T(); // enough with the old x
::new (&x) T(22, Brown, true); // in with the new!
// ...
}
在作用域的末尾,析构函数将再次运行,一切似乎都很好。 (我们还可以说 T
有点特殊,不喜欢被赋值,更不用说交换了。)但是有件事告诉我,摧毁一切并重试并非总是没有风险。这种方法可能有问题吗?
最佳答案
我认为使它真正安全使用的唯一方法是要求被调用的构造函数是noexcept
,例如通过添加static_assert
:
static_assert(noexcept(T(22, Brown, true)), "The constructor must be noexcept for inplace reconstruction");
T x(31, Blue, false);
x.~T();
::new (&x) T(22, Brown, true);
当然这只适用于 C++11。
关于c++ - 使用相同的变量销毁然后构造新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9155737/