2 c++
当我尝试检查是否str[index]等于我得到异常字符串超出范围时
std::string Test::getTheText(std::string str) {
int index = 7;
string text;
cout << str[index] << endl; // Work!!
while (str[index] != '\"') // Exception,why?? also try while(str[index]!=34)
text += str[index++];
return text;
}
Run Code Online (Sandbox Code Playgroud)
我的字符串是:文本– bla bla
为什么下面的代码有效?
Run Code Online (Sandbox Code Playgroud)std::string str = "bla bla"; int index = 7; cout << str[index] << endl; // Work!!
如果index等于字符串的长度(在您的情况下为,7 == strlen("bla bla")),访问运算符将返回对实例化默认值charTin 的引用std::basic_string<charT>,因为char它是\0。
如果pos 不大于字符串长度,则该函数从不抛出异常(无抛出保证)。
但是,稍后您尝试访问另一个元素:
str[index++] // in second iteration, the first is ok though
Run Code Online (Sandbox Code Playgroud)
而只有你掉进:
[...],它导致未定义的行为。
C ++标准参考:
§21.4.5 basic_string元素访问[string.access]
Run Code Online (Sandbox Code Playgroud)const_reference operator[](size_type pos) const; reference operator[](size_type pos);
要求:
pos <= size()返回:
*(begin() + pos)如果pos < size()。否则,返回对类型charT为value 的对象的引用charT(),其中修改对象会导致未定义的行为。抛出: 没事。
也就是说,只要pos <= size()满足条件,该方法就不会抛出,否则行为是Undefined,抛出异常就是示例之一。