Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Please check change to "capacity-size characters" in 2nd compliant solution

The basic_string template class has unusual invalidation semantics. 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:

  • As as an argument to non-member functions swap(), operator>>(), and getline().
  • As as an argument to basic_string::swap().
  • Calling calling data() and c_str() member functions.
  • Wiki Markup
    Callingcalling non-const member functions, except {{operator\[\]()}}, {{at()}}, {{begin()}}, {{rbegin()}}, {{end()}}, and {{rend()}}.
  • Wiki Markup
    Subsequentsubsequent to any of the above uses except the forms of {{insert()}} and {{erase()}} whichthat return iterators, the first call to non-const member functions {{operator\[\]()}}, {{at()}}, {{begin()}}, {{rbegin()}}, {{end()}}, or {{rend()}}.

Non-Compliant Code Example

...

In this non-compliant example, the string s is initialized as "rcs" and the string iterator si is initialized to the beginning of the string. The size of s is three, and we'll assume the capacity is fifteen. The for loop appends 20 characters to the end of the sting. As a result, the si iterator is invalided invalidated because the capacity of the string is exceeded, requiring a reallocation. As a result, the call to insert() results in undefined behavior.

...

The relationship between size and capacity makes it possible to predict when a call to a non-const member function will cause a string to perform a reallocation. This in turn makes it possible to predice predict when an insertion will invalidate references, pointers, and iterators (to anything other than the end of the string).

...

If instead of performing a push_back(), the code were to insert into an arbitrary location in the string, all references, pointers, and iterators from the insertion point to the end of the string are would be invalidated.

Exceptions

The intent of these iterator invalidation rules is to give implementors greater freedom in implementation techniques. Some implementations implement method versions that do not invalidate references, pointers, and iterators in all cases. Check with the documentation for your implementation before attempting to access a (potentially) invalid iterator. Document any violation of the semantics specified by the standard for portability.

...