Is `new (this) MyClass();` undefined behaviour after directly calling the destructor?

心不动则不痛 提交于 2019-11-28 13:27:44

That would be okay if it didn't conflict with stack unwinding.

You destroy the object, then reconstruct it via the pointer. That's what you would do if you needed to construct and destroy an array of objects that don't have a default constructor.

The problem is this is exception unsafe. What if calling the constructor throws an exception and stack is unwound and the destructor is called for the second time?

{
   X x;
   x.foo(); // here ~X succeeds, then construction fails
} //then the destructor is invoked for the second time.

That aspect specifically would be undefined behavior.

Apart from @sharptooth's answer. I am just wondering for 2 more cases. At least they are worth mentioning.

(1) If the foo() was invoked using a pointer on heap which was allocated using malloc(). The constructor is not called. Can it be safe ?

(2) What if the derived class is calling foo(). Will it be a good behavior ? e.g.

struct Y : X {};  // especially when there is virtual ~X()
int main ()
{
  Y y;
  y.foo();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!