The Since std::basic_string
is a container of characters, this rule is a specific instance of CTR51-CPP. Use valid references, pointers, and iterators to reference elements of a container. As a container, it supports iterators just like other containers in the Standard Template Library. However, the std::basic_string
template class has unusual invalidation semantics. According to the C++ Standard, [string.require], paragraph 5 [ISO/IEC 14882-2014]:
References, pointers, and iterators referring to the elements of a
basic_string
sequence may be invalidated by the following uses of thatbasic_string
object:
- As an argument to any standard library function taking a reference to non-const
basic_string
as an argument.- Calling non-const member functions, except
operator[]
,at
,front
,back
,begin
,rbegin
,end
, andrend
.
...
Do not use an invalidated reference, pointer, or iterator because doing so results in undefined behavior.Since std::basic_string
is a container of characters, this rule is a specific instance of CTR51-CPP. Use valid references, pointers, and iterators to reference elements of a container.
Noncompliant Code Example
This noncompliant code example copies input
into a std::string
, replacing semicolon (;)
characters with spaces. This example is noncompliant because the iterator loc
is invalidated after the first call to insert()
. The behavior of subsequent calls to insert()
is undefined.
...
Code Block | ||||
---|---|---|---|---|
| ||||
#include <algorithm> #include <string> void f(const std::string &input) { std::string email{input}; std::replace(email.begin(), email.end(), ';', ' '); } |
Noncompliant Code Example
In this noncompliant code example, data
is invalidated after the call to replace()
, and so its use in g()
is undefined behavior:
...