Search code examples
c++placement-new

Is it dangerous to use placement new on an old object without explicitly calling the destructor first?


I would like to recycle memory for an object rather than deallocating and reconstructing it. Is the following usage of "placement new" safe, assuming that Foo in practice does not contain pointers (but might contain functions)?

Also, is the final delete call safe, and will it correctly call the destructor on the second "new" object, and correctly free the memory afterwards?

#include <new>
struct Foo {
    int hello;
    int world;
};

int main() {
    Foo* foo = new Foo;
    // Do something with foo
    // Done with foo, writing a new version of foo on top of the old one.
    new(foo) Foo();

    delete(foo);
}

The simple example above compiles and runs without errors, but I cannot tell by running it whether it might blow up for some reason in a more complex environment.


Solution

  • No, it is not dangerous to reuse memory of an object, provided that you are doing it correctly. Moreover, you do not have to restrict yourself to objects that have no pointers: by calling the destructor explicitly you can prepare the object for reuse, like this:

    Foo* foo = new Foo;
    // Do something with foo
    // Done with foo, writing a new version of foo on top of the old one.
    foo->~Foo();     // Call the destructor explicitly to clean up the resources of a Foo
    new(foo) Foo();  // Place new data into the previously allocated memory
    delete(foo);     // We are deleting a fully initialized object, so it is OK