为什么即使尚未初始化字符串[0]也有效?

时间:2017-04-03 03:45:15

标签: c++ string c++11 language-lawyer

考虑这段代码

string str;
cout << str[0] << str.size();

我得到的不是运行时错误,而是" 0"0跟空格。为什么这可能?

1 个答案:

答案 0 :(得分:9)

str未初始化,default initalized为空std::string;即其size()0。从C ++ 11开始,该标准要求std::basic_string::operator[]返回对此案例的空字符的引用。

  

如果pos == size(),则返回对值为CharT()(空字符)的字符的引用。

值得注意的是,在C ++ 11之前,对于operator[]的非const版本,这是未定义的行为,对于const版本,将返回对null字符的引用;并且由于非const版本的C ++ 11,对返回引用上的其他字符的任何修改都是未定义的行为。

顺便说一句:Undefined behavior意味着一切皆有可能;它不一定是运行时错误。