What is the defined behavior of std :: string :: erase () with a pos of string :: npos?

advertisements

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?


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.