Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why string constructor(s, pos) exception is "pos > s.size()" and not "pos >= s.size()"?

Tags:

c++

c++20

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()"?

like image 805
yapkm01 Avatar asked Oct 12 '25 11:10

yapkm01


2 Answers

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.

like image 65
Ted Lyngmo Avatar answered Oct 13 '25 23:10

Ted Lyngmo


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.

like image 39
Remy Lebeau Avatar answered Oct 13 '25 23:10

Remy Lebeau