tags:

views:

94

answers:

2

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

+4  A: 

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 );
}
anon
Neil, is there a reason you're having `tmp` or is that just a question of style and personal preferences?
sbi
@sbi Both :-) And I think it's clearer.
anon
@Neil: Yeah, my wording was bad, I meant to ask whether there's a _technical_ reason. Anyway, thanks for answering. I might have been poisoned by the _C Terseness Virus_, but I actually do prefer `std::vector<T>().swap(v)`.
sbi
+1  A: 

Consider using the swap trick:

vector(shapes).swap(shapes);

Alex M.