2

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.

billz
  • 44,644
  • 9
  • 83
  • 100
user2015453
  • 4,844
  • 5
  • 25
  • 27
  • 1
    Please decrease the size of the title and put the question details into the question text. May even make the question more understandable. – Ed Heal Feb 24 '13 at 10:35
  • 2
    These are not "the docs" for anything. Prefer http://cppreference.com or [a good book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Lightness Races in Orbit Feb 24 '13 at 10:36

2 Answers2

3

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.”

Cheers and hth. - Alf
  • 142,714
  • 15
  • 209
  • 331
Roee Gavirel
  • 18,955
  • 12
  • 67
  • 94
  • +1 for first correct answer. i misinterpreted the question and provided an incorrect answer. :-( deleted... – Cheers and hth. - Alf Feb 24 '13 at 10:45
  • 1
    @Cheersandhth.-Alf no wonder at the misunderstanding, because someone edited the title into something totally different than what I intended. fixed – user2015453 Feb 24 '13 at 10:46
  • Yes, that's what I thought. So is this "one-past-end" just something that is just "well-known" so the docs don't even have to bother mentioning this case? This "one-past-end" indeed looks like a pretty prevalent concept in the C++ world... – user2015453 Feb 24 '13 at 10:47
2

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.

alestanis
  • 21,519
  • 4
  • 48
  • 67