patterncppModerate
Deallocate all memory in a container of pointers
Viewed 0 times
containeralldeallocatepointersmemory
Problem
I want to erase all memory in a container. Currently I'm using this :
template
void clear_mem(Cont &container)
{
while (!container.empty())
{
delete container.back();
container.pop_back();
}
}- Should the operation of deleting the memory held by the contents be separated by clearing the container ?
- Is it pointless to make this function a template, since it can only operate on vector and list ?
Solution
This assumes that the container holds raw pointer and it owns the pointers. it is a better idea to then let the container hold smart pointers.
These will automatically clear the object they hold when they get destroyed (using
and use emplace to fill it;
These will automatically clear the object they hold when they get destroyed (using
delete by default).typedef std::unique_ptr Type_ptr;
std::vector container;and use emplace to fill it;
container.emplace_back(std::make_unique());Code Snippets
typedef std::unique_ptr<Type> Type_ptr;
std::vector<Type_ptr> container;container.emplace_back(std::make_unique<Type>());Context
StackExchange Code Review Q#51129, answer score: 10
Revisions (0)
No revisions yet.