[英]Memory release of boost::shared_ptr of std::vector
I'm trying to release the memory of a boost::shared_ptr<std::vector<std::vector<std::vector<int> > > >
using the following code: 我正在尝试使用以下代码释放
boost::shared_ptr<std::vector<std::vector<std::vector<int> > > >
的内存:
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.
我用htop命令检查过,使用的内存与我从未释放过的对象相同。
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.
也许这与shared_ptr有关,因为我之前发布了没有指针的向量,并且它起作用了。
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. shared_ptr不会超出范围,因为它是在睡眠线程中保持执行状态的对象的类成员。
If you have a std::shared_ptr<std::vector>>
and you want to delete it: 如果您有
std::shared_ptr<std::vector>>
并要删除它:
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>>
并想将其清空:
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.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 如果您担心
htop
不会为进程显示减少的分配内存量,那么我们就可以将其标记为该帖子的副本: vector <string>在超出范围后不会清除内存
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.