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
?
No. You never need to explicitly call a destructor (except with placement new ). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete .
If destructor is not declared, compiler will generate destructor, that will call destructors of all members of object. Leak can be only if you are working with raw-memory (C files, memory allocation etc).
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?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With