Search code examples
c++vectordequegotw

Why not resize and clear works in GotW 54?


Referring to article Gotw 54 by HerbSutter, he explains about

  1. The Right Way To "Shrink-To-Fit" a vector or deque and

  2. The Right Way to Completely Clear a vector or deque

Can we just use container.resize() and container.clear() for the above task or am I missing something?


Solution

  • There are two different things that a vector holds: size Vs capacity. If you just resize the vector, there is no guarantee that the capacity(how much memory is reserved) must change. resize is an operation concerned with how much are you using, not how much the vector capacity is.

    So for example.

    size     == how much you are using
    capacity == how much memory is reserved
    vector<int> v(10);
    
    v.resize(5); // size == 5 but capacity (may or may) not be changed
    v.clear()    // size == 0 but capacity (may or may) not be changed
    

    In the end, capacity should not changed on every operation, because that would bring a lot of memory allocation/deallocation overhead. He is saying that if you need to "deallocate" the memory reserved by vector, do that.