Why doesn't vector::clear remove elements from a vector?

前端 未结 10 2403
我寻月下人不归
我寻月下人不归 2020-11-29 07:29

When I use clear() on a std::vector, it is supposed to destroy all the elements in the vector, but instead it doesn\'t.

Sample

10条回答
  •  清酒与你
    2020-11-29 08:03

    From cppreference:

    void clear();
    

    Removes all elements from the container. Invalidates any references, pointers, or iterators referring to contained elements. May invalidate any past-the-end iterators. Many implementations will not release allocated memory after a call to clear(), effectively leaving the capacity of the vector unchanged.

    So the reason there is no apparent problem is because the vector still has the memory available in store. Of course this is merely implementation-specific, but not a bug. Besides, as the other answers point out, your program also does have Undefined Behavior for accessing the cleared contents in the first place, so technically anything can happen.

提交回复
热议问题