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

StackOverflow https://stackoverflow.com/questions/10546695

سؤال

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 ?

هل كانت مفيدة؟

المحلول

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)

نصائح أخرى

Technically speaking, assuming that the destructor doesn't release any resources acquired during construction, it may not be necessary.

However, considering the non-technical aspects - maintenance and evolution of the code - I would stick to the best practice - what was constructed, should be destructed. Scenario to consider - what if in the future some changes will determine relevant code to be put in the destructor? Will you remember that you skept the destruction of that type of object?

If your class handles some resources(heap memory, handles, counters, mutexes...) or contains some fields which handle resources, this resources will be not freed if you do not call destructor explicitly. Otherwise there no any troubles with destruction. You can consider non-destructed class as a garbage in memory and construct new one freely in the same place.

Yes, you have to call destructor explicitly (please keep in mind side-effects of T, i.e. freeing some additional memory). Also, you have to be careful about memory alignment when using placement new.

If you wish, you could reuse buffer memory.

Please also refer to http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.14

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top