Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 886
iammilind Avatar asked May 11 '12 06:05

iammilind


People also ask

Do destructors need to be called?

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.

Are class destructors called automatically?

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 .

What happens if the programmer is not creating a destructor in a custom type?

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).


2 Answers

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?

like image 69
Cătălin Pitiș Avatar answered Sep 17 '22 21:09

Cătălin Pitiș


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)

like image 21
CB Bailey Avatar answered Sep 20 '22 21:09

CB Bailey