有时重新开始很好.在C++中,我可以使用以下简单的操作:
{
T x(31, Blue, false);
x.~T(); // enough with the old x
::new (&x) T(22, Brown, true); // in with the new!
// ...
}
Run Code Online (Sandbox Code Playgroud)
在范围的最后,析构函数将再次运行,一切似乎都很好.(我们也说T有点特别,不喜欢被分配,更不用说交换了.)但有些东西告诉我,摧毁一切并再试一次并不总是没有风险.这种方法有可能存在吗?
例如:
class Foo : public Bar
{
~Foo()
{
// Do some complicated stuff
}
Foo &operator=(const Foo &rhs)
{
if (&rhs != this)
{
~Foo(); // Is this safe?
// Do more stuff
}
}
}
Run Code Online (Sandbox Code Playgroud)
在继承和其他类似的事情上明确调用析构函数会产生什么意外后果吗?
有没有理由将析构函数代码抽象为void destruct()函数并调用它?