C++ Is constructing object twice using placement new undefined behaviour?

谁都会走 提交于 2019-11-29 07:19:57

Generally, working with placement new in this way is not a good idea. Calling an initializer from the first new, or calling an initializer instead of placement new are both considered to be better form than the code you've provided.

However, in this case, the behaviour of calling placement new over an existing object is well defined.

A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

So when this happens:

Foo* fooArray = new Foo[numFoos];   //allocate an array of default constructed Foo's

for(int i = 0; i < numFoos; ++i)
{
    new( fooArray+ i) Foo( initialiser );    //use placement new to initialise
}

The placement new operation will end the lifetime of the Foo that was there, and create a new one in it's place. In many circumstances this could be bad, but given the way your destructor works, this will be fine.

Calling placement new on an existing object could be undefined behaviour, but it depends on the specific object.

This does not produce undefined behaviour, because you are not depending on the "side effects" produced by the destructor.

The only "side-effect" in the destructor of your object is to delete the contained int pointer, but in this case that object is never in a deletable state when placement new is called.

If it was possible for the contained int pointer to be equal to something other than nullptr and could possibly require deleting, then calling placement new over the existing object would invoke undefined behaviour.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!