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

2019-02-08 14:18发布

问题:

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

回答1:

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


回答2:

Consider using the swap trick:

vector(shapes).swap(shapes);



标签: c++ vector