有效的向量清晰向量C ++ [英] Clear vector of vectors effectively C++

查看:92
本文介绍了有效的向量清晰向量C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了需要创建2层或3层嵌套向量的问题,但是我遇到了无法正确清除内存的问题.所以我做了一个简单的测试:

I came across having the need to create 2 or 3-level nested vectors but I had this issue of memory not clearing correctly. So I made this simple test:

void test(){
vector<vector<double>> myContainer;

vector<double> vec = {1};
for (int i=0; i<20000000; ++i)
{
    myContainer.push_back(vec);
}
FreeAll(myContainer);
}    

其中FreeAll()是定义如下的模板函数:

where FreeAll() is a template function defined as follows:

template <typename T>
void FreeAll( T & t ) {
T tmp;
t.swap(tmp);
}

现在,在main()中调用函数test(),我们将发现,即使在离开测试函数的作用域之后,仍有许多剩余的内存,并且直到主线程终止后,才会清除内存.

Now, invoking function test() in main(), we will find out that a lot of left over memory is still there even after leaving the test function's scope and that memory is not cleared up until the main terminates.

这可能是我创建过多向量的原因吗?此外,这里没有任何类型的内存泄漏,因为所有存储都是自动的.

Could be the reason for this that I create too much vectors? also there is no any kind of memory leak here as all the storage is automatic.

推荐答案

在这种情况下,没有任何类型的内存泄漏,并且从Ubuntu的默认系统监视器中也没有出现内存观察.

In this very context, there is no any sort of memory leaks and memory observations occurred from Ubuntu's default system monitor.

因此在main()中调用test()4次,并检查最后3次调用是否会分配更多的内存或从先前的分配中重用它,结果是不会分配更多的内存,并且该内存确实可重用,只有程序终止后,它才会被释放.相反,创建一个double的向量并推动相同数量的double并调用FreeAll(),它将实际上立即释放内存并将其返回给OS.

So calling test() 4 times in main() and check if the last 3 calls would allocate more memory or reuse it from the previous allocation and it turns out that no more memory would be allocated and the memory is indeed reusable and it will be only freed once the program terminates. On the contrary, creating a vector of double and pushing the same number of doubles and call FreeAll(), it will actually free the memory instantly and it's returned to the OS.

这篇关于有效的向量清晰向量C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆