What does the C++11 standard specify for the behavior of the string& erase (size_t pos = 0, size_t len = npos);
member function when the pos
argument is passed as string::npos
? I would think it should erase nothing, but perhaps it throws an out_of_range
exception instead? What is the defined behavior for the standard?

- 106,671
- 19
- 240
- 328

- 41,123
- 68
- 193
- 295
2 Answers
It throws std::out_of_range
, as specifically stated in the standard:
21.4.6.5 basic_string::erase [string::erase]
basic_string& erase(size_type pos = 0, size_type n = npos);
Requires:
pos <= size()
Throws:
out_of_range
ifpos > size()
.Effects: Determines the effective length
xlen
of the string to be removed as the
smaller ofn
andsize() - pos
. The function then replaces the string controlled by*this
with a string of lengthsize() - xlen
whose firstpos
elements are a copy of the initial elements of the original string controlled by*this
, and whose remaining elements are a copy of the elements of the original string controlled by*this
beginning at positionpos + xlen
.Returns:
*this
.

- 55,410
- 12
- 139
- 252
It throws std::out_of_range
. See http://en.cppreference.com/w/cpp/string/basic_string/erase.
The general principle is that values ofpos
between 0 and size()
(i.e. one past the end) are fine, but anything beyond that indicates caller error.

- 18,815
- 3
- 45
- 64