Will a call to std::vector::clear() set std::vecto

2019-01-14 20:23发布

问题:

If I use .reserve(items) on a vector, the vector will allocate enough memory for my guess of the number of items that I'll need.

If I later on use .clear(), will that just clear the vector or save my earlier defined reserve?

thanks.

回答1:

It is specified that std::vector<T>::clear() affects the size. It might not affect the capacity. For resetting the capacity, use the swap trick:

    std::vector<int> v1;

    // somehow increase capacity

    std::vector<int>().swap(v1);

Note: Since this old answer is still getting upvotes (thus people read it), I feel the need to add that C++11 has added std::vector<...>::shrink_to_fit(), which requests the vector to remove unused capacity.



回答2:

It will probably not release the reserved memory although I don't think the behaviour is specified in the standard.

EDIT: Ok, just checked and the standard only says that the post-condition is that size() == 0 although I haven't come across a vector implementation that doesn't hold on to the reserved memory.



回答3:

No it won't. Try it out by calling vector::capacity().

Further evidence of this is the appearance of shrink_to_fit. The standard's working draft mentions:

Remarks: shrink_to_fit is a non-binding request to reduce capacity() to size(). [ Note: The request is non-binding to allow latitude for implementation-specific optimizations. —end note ]



回答4:

No, it won't set reserve() to 0. Calling clear() calls the destructors of each element and removes them from the vector, leaving the container with size of 0, but the capacity remains unchanged.



回答5:

It will not affect the underlying buffer size. Which is why you have to use tricks like this to actually get rid of the buffer or make it smaller.



标签: c++ stl vector