Reputation: 760
I'm trying to release the memory of a boost::shared_ptr<std::vector<std::vector<std::vector<int> > > >
using the following code:
vec->clear();
std::vector<std::vector<std::vector<int> > > (*vec).swap(*vec);
But for some reason it isn't working. I checked with htop command and the memory used is the same as I've never released the object.
Then I tried to release each vector separately like:
for (auto it1 : *vec)
{
for (auto it2 : it1)
{
it2.clear();
std::vector<int>(it2).swap(it2);
}
it1.clear();
std::vector<int>(it1).swap(it1);
}
But still consumes the same amount of memory.
Am I doing something wrong? Maybe it has to do with the shared_ptr because I've released vectors without pointers before and it worked.
Update
The shared_ptr won't get out of scope since is a class member of an object that remains in execution in a sleeping thread.
Upvotes: 0
Views: 676
Reputation: 81986
If you have a std::shared_ptr<std::vector>>
and you want to delete it:
std::shared_ptr<std::vector<T>> ptr = ...;
ptr.reset();
If you have a std::vector<std::shared_ptr<T>>
and you want to empty it:
std::vector<std::shared_ptr<T>> vec = ...;
vec.clear();
If you have a std::vector<T>
and you want the vec.capacity() == vec.size()
:
std::vector<T> vec = ...;
vec.shrink_to_fit(); // or: std::vector<T>(vec).swap(vec);
If you are concerned that htop
doesn't show a reduced amount of allocated memory to the process, then let's just mark this as a duplicate of this post: vector<string> does not clear memory after out of scope
Upvotes: 1