强制std :: vector释放它的内存? [英] Force a std::vector to free its memory?
问题描述
可能的重复项:
减少stl向量的容量
我知道当你调用vector.clear()时,std :: vector不会释放内存,但是我该怎么做呢?我想让它释放所有的资源,一旦我清除它,但我不想毁灭它。
I know that std::vectors do not 'free' the memory when you call vector.clear(), but how can I do this? I want it to release all of its resources once I clear it but I don't want to destroy it.
这里是现在发生了什么。
我有一个类叫OGLSHAPE,我把它们推入它们的向量。我希望,一旦我做了shapevec.clear()我会得到我的记忆,但只有3/4的回来。我不是100%肯定如果这是一个内存泄漏或不是所以我想释放所有的资源,以确保它不是一个泄漏。感谢
Here is what is happening right now. I have a class called OGLSHAPE and I push these into a vector of them. I was hoping that once I did shapevec.clear() I'd get all my memory back, but only got 3/4 of it back. I'm not 100% sure if this is a memory leak or not so I want to free all the resources to be sure its not a leak. Thanks
推荐答案
使用交换技巧:
#include <vector>
template <typename T>
void FreeAll( T & t ) {
T tmp;
t.swap( tmp );
}
int main() {
std::vector <int> v;
v.push_back( 1 );
FreeAll( v );
}
这篇关于强制std :: vector释放它的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!