Search code examples
c++destructorplacement-newexplicit-destructor-call

Do we need to explicitly call the destructor for the "simple POD classes" allocated with "placement new"?


Here by "simple", I mean a class with non-virtual empty destructor or POD type.

Typical example:

char buffer[SIZE];
T *p = new(buffer) T;
...
p->~T();  // <---- always ?

What happens if we don't call the explicit destructor on p? I don't think it is undefined behavior or memory leak.
Is there any problem with reusing buffer ?


Solution

  • For a POD-type or a class with a trivial destructor: no. The lifetime of the object will end when the storage for the object is released or reused. You don't have to call the destructor explicitly if you don't want to.

    That said, there's no reason not to. For a type with a trivial destructor the destructor call will generate no code.

    If, by a class with an "empty" destructor you are allowing the possibility the class has members or base classes with non-trivial destructors then you may get undefined behaviour if your program relies on these destructors being called.

    Note that a user provided destructor is a non-trivial destructor even if it is non-virtual and is empty. Despite this you are still permitted to end the lifetime of an object with such a destructor by simply releasing or reusing its storage provided that your program doesn't depend on any side effects of the destructor. (See 3.8 [basic.life] / 4 of ISO/IEC 14882:2011)