user7242858
user7242858

Reputation: 81

Placement new and destructor

I have simple struct that has fixed size and contains build-in types. I create memory pool by allocating chunk of memory and I split this memory to blocks of size of my struct. Then it uses placement new to call constructor on particular memory block to initialize some members with default values. Then I would like to release whole memory chunk by calling delete[] operator. Can I safely skip explicit destructor call for each object initialized with placement new? I don't locate any resources inside constructor or inside constructors of other member fields of that class. I want just release whole memory chunk.

Upvotes: 3

Views: 1140

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

You can skip a call to destructor if it is trivial:

A trivial destructor is a destructor that performs no action. Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage.

You can tell if the type is trivially destructible using std::is_trivially_destructible<Type>::value expression. If you compile with optimization on, most optimizers will figure this out for you, so there will be no performance hit for writing a loop that calls trivial destructors for all objects in the block.

Upvotes: 4

Related Questions