user2015453
user2015453

Reputation: 5104

What happens when calling the str.erase with "pos" equal to the string's length?

The docs for the string erase(pos,len) function doesn't specify very clearly what exactly happens if pos happens to be "one-past-end" of the string. It only hints that this is not forbidden, but not mentioning specifically what this special case means.

Indeed, str.erase(str.size()) does NOT throw an exception.

What is really supposed happen in this case? This seems not mentioned anywhere explicitly.

Upvotes: 2

Views: 169

Answers (2)

Roee Gavirel
Roee Gavirel

Reputation: 19445

It's not that "spacial case".
Same as str.erase(0,0); will not do anything. str.erase(str.size()); is telling it to delete all chars form the end to the end. which erase nothing.

C++11 §21.4.6.5: “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.”

Upvotes: 3

alestanis
alestanis

Reputation: 21863

It's written in your link that

If pos is greater than the string length, an out_of_range exception is thrown.

I think that answers the question.

Upvotes: 2

Related Questions