Substr exception, pos string length

In the substr documentation it says:
http://www.cplusplus.com/reference/string/string/substr/
string substr (size_t pos = 0, size_t len = npos) const;
If pos is greater than the string length, an out_of_range exception is thrown.


Basically, my question is why an exception is thrown only when pos is greater than the string length, shouldn't it still be bad if pos is equal to or greater than the string length, since the length number can't be an array index?

Little snippet of code I was working with:
1
2
3
4
5
6
7
8
9
10
11
12
13
    //example of possible inputs
    std::string lineR;
    //a good "line" would be something like "abc=100"
    std::string line = "zzz="; //Nothing is after the '='!
    size_t equal_sign_pos = line.find('='); //assuming it isn't string::npos

    //actual code:
    try {
        lineR = line.substr(equal_sign_pos + 1);
    } catch (const std::out_of_range& oor) {
        std::cerr << "Out of Range error: " << oor.what() << '\n';
        return false;
    }

I was at first surprised that this didn't throw an exception.
So, to clarify, in the above code, will lineR always be assigned an empty string? Is the whole try-catch part of my code redundant because I'm only going 1 over the equal_sign_pos?
Last edited on
Same page says:
pos
Position of the first character to be copied as a substring.
If this is equal to the string length, the function returns an empty string.
If this is greater than the string length, it throws out_of_range.


Then look at http://www.cplusplus.com/reference/string/string/c_str/
and notice that the internal array does contain a null after the string.
Wow, so it says it right there... an empty string. I thought I had read it all twice before making sure I wasn't asking a stupid question, alas! Thanks. (Seriously no idea how I missed that line)
Last edited on
Topic archived. No new replies allowed.