How do vector::empty, clear, erase, resize, capacity, and shrink_to_fit differ in observation, element lifetime, memory reuse, and invalidation?
Show answer and explanation
empty only observes whether size is zero. clear destroys every element and sets size to zero while retaining capacity for reuse; resize(0) also removes every element without being a request to reduce capacity. erase removes a selected range and shifts later elements, invalidating iterators and references at or after the erased position. References and iterators to elements destroyed by clear or resize are invalid, and the past-the-end iterator changes. shrink_to_fit is a non-binding request to reduce capacity to size; if it reallocates, every pointer, reference, and iterator into the vector is invalidated. Destroying the vector releases its owned allocation through its allocator; assigning replacement contents may reuse existing capacity and does not guarantee deallocation. Retaining capacity is often desirable for repeated workloads, so release memory only when measurements and ownership boundaries justify it.
empty only observes whether size is zero. clear destroys every element and sets size to zero while retaining capacity for reuse; resize(0) also removes every element without being a request to reduce capacity. erase removes a selected range and shifts later elements, invalidating iterators and references at or after the erased position. References and iterators to elements destroyed by clear or resize are invalid, and the past-the-end iterator changes. shrink_to_fit is a non-binding request to reduce capacity to size; if it reallocates, every pointer, reference, and iterator into the vector is invalidated. Destroying the vector releases its owned allocation through its allocator; assigning replacement contents may reuse existing capacity and does not guarantee deallocation. Retaining capacity is often desirable for repeated workloads, so release memory only when measurements and ownership boundaries justify it.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.