2

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?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
WilliamKF
  • 41,123
  • 68
  • 193
  • 295

2 Answers2

3

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 if pos > size().

Effects: Determines the effective length xlen of the string to be removed as the
smaller of n and size() - pos. The function then replaces the string controlled by *this with a string of length size() - xlen whose first pos 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 position pos + xlen.

Returns: *this.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
1

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.

Alan Stokes
  • 18,815
  • 3
  • 45
  • 64