user1432882
user1432882

Reputation: 1152

Do I still need to call a destructor of a std::container if both the container and allocator are part of the same memory pool?

(Using Thread Building Blocks memory pool in example)

Lets say I have the following setup:

using MemoryPool = tbb::memory_pool<std::allocator<char>>;
using CustomAllocator = tbb::memory_pool_allocator<Result*>;
using CustomVector = std::vector<Result*, CustomAllocator>;

MemoryPool shortTermPool;
void* allocatedMemory = shortTermPool.malloc(sizeof(CustomVector);
CustomVector* results = static_cast<CustomVector*>(allocatedMemory);
new(results) CustomVector(CustomAllocator(shortTemPool));

Later I call

shortTermPool.recycle(); 

This line of code recycles all the memory in the memory pool, allowing me to reuse it. Now, since both the vector and it's allocator are using the memory pool, do I still need to call

results->~vector();

before recycling the memory pool? Is the destructor doing anything additional, or will recycling the entire pool be enough?

Upvotes: 1

Views: 222

Answers (1)

alain
alain

Reputation: 12057

From the C++ standard:

3.8 Object lifetime

4 A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor. For an object of a class type with a non-trivial destructor, the program is not required to call the destructor explicitly before the storage which the object occupies is reused or released; however, if there is no explicit call to the destructor or if a delete-expression (5.3.5) is not used to release the storage, the destructor shall not be implicitly called and any program that depends on the side effects produced by the destructor has undefined behavior.

It depends on whether the std::vector destructor is non-trivial and has side effects on which the program depends. Because it is a library class, it would be advisable to call the destructor to be safe. Else you would have to check the std::vector implementations now and in the future for all standard libraries you want your code to be compatible with.
If the vector class was your own, you would be in control of the destructor implementation and you could omit calling it if it was either trivial, or had no side-effects on which the program depends, as described above.
(But personally I would also call it in this case.)

Upvotes: 1

Related Questions