开发者

Force a std::vector to free its memory? [duplicate]

This question already has answers here: Closed 12 years ago. 开发者_如何学JAVA

Possible Duplicates:

reduce the capacity of an stl vector

Is this normal behavior for a 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.

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


Use the swap trick:

#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 );
}


Consider using the swap trick:

std::vector<Shape>().swap(shapes);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜