问题描述
有时很好,重新开始。在C ++中,我可以使用以下简单的操作:
Sometimes it's nice to start over. In C++ I can employ this following simple manoeuvre:
{
T x(31, Blue, false);
x.~T(); // enough with the old x
::new (&x) T(22, Brown, true); // in with the new!
// ...
}
的范围,析构函数将再次运行,一切似乎很好。 (让我们还说 T
有点特别,不喜欢被分配,更不用说交换了。)但是有些东西告诉我,毁灭一切并不总是没有风险,再次。使用这种方法有可能捕获吗?
At the end of the scope, the destructor will run once again and all seems well. (Let's also say T
is a bit special and doesn't like being assigned, let alone swapped.) But something tells me that it's not always without risk to destroy everything and try again. Is there a possible catch with this approach?
推荐答案
我认为唯一的方法是让这个真正安全的使用是要求称为构造函数 noexcept
,例如通过添加 static_assert
:
I think the only way to make this really safe to use is to require the called constructor to be noexcept
, for example by adding a 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。
Of course this will only work for C++11.
这篇关于使用相同的变量销毁并构造新对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!