Search code examples
c++stringvectorstandardsc++20

Does std::string::resize(smaller_than_capacity) guarantee existing iterators are still valid?


According to cppref, std::vector::resize explicitly guarantees:

Vector capacity is never reduced when resizing to smaller size because that would invalidate all iterators, rather than only the ones that would be invalidated by the equivalent sequence of pop_back() calls.

However, I cannot find any similar guarantee from the documentation of std::string::resize.

Does std::string::resize(smaller_than_capacity) guarantee existing iterators are still valid?


Solution

  • Such requirement does not exist in Standard. See 21.3.3.2:

    References, pointers, and iterators referring to the elements of a basic_­string sequence may be invalidated by the following uses of that basic_­string object:

    (4.1) Passing as an argument to any standard library function taking a reference to non-const basic_­string as an argument.

    (4.2) Calling non-const member functions, except operator[], at, data, front, back, begin, rbegin, end, and rend.