Sample below:
string s1 = "abcde";
string s2(s1, s1.size()); // s1.size() = 5.
Notice that s1.size() = 5 and the last allowable index = 4 (for character 'e'). The above runs fine returning empty string. Only when pos = 6 then it fail with exception out-of-range. Why?
According to cppereference site:
Exceptions
3) std::out_of_range if pos > other.size()
Shouldn't the correct exception be "if pos >= other.size()"?
Since C++11, s1[s1.size()]
is required to work and will return a reference to the '\0'
at the end of the string. Changing the '\0'
to something else however leads to undefined behavior. You are however allowed to write '\0'
there.
Notice that
s1.size() = 5
and the last allowable index = 4 (for character 'e').
This is wrong. Since C++11, the last allowable character index is size()
, not size()-1
. std::basic_string
's data buffer is now required to be null terminated, and accessing index size()
(even on an empty string) is required to return a reference to a valid '\0'
character.
The above runs fine returning empty string.
As it should be.
Only when pos = 6 then it fail with exception out-of-range.
Correct, because that really is out of bounds.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With