14

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

Community
  • 1
  • 1
jmasterx
  • 52,639
  • 96
  • 311
  • 557

2 Answers2

16

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 );
}
  • 1
    Neil, is there a reason you're having `tmp` or is that just a question of style and personal preferences? – sbi Jul 03 '10 at 20:56
  • @sbi Both :-) And I think it's clearer. –  Jul 03 '10 at 20:59
  • 3
    @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().swap(v)`. – sbi Jul 03 '10 at 21:08
2

Consider using the swap trick:

std::vector<Shape>().swap(shapes);
AndreyS Scherbakov
  • 2,674
  • 2
  • 20
  • 27
nas
  • 957
  • 1
  • 9
  • 21