c++ - 为什么在没有初始化的情况下获取string[0]也是有效的?

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

考虑这段代码

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

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

最佳答案

str 不是未初始化的,它是 default initalized作为一个空的 std::string;即它的 size()0。从 C++11 开始,标准需要 std::basic_string::operator[]为这种情况返回对空字符的引用。

If pos == size(), a reference to the character with value CharT() (the null character) is returned.

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

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

关于c++ - 为什么在没有初始化的情况下获取string[0]也是有效的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43176196/

相关文章:

C++ 字符串和分隔符

c++ - 错误 : no instance of overloaded function "std::make_shared" matches the argument list

c++ - 将错误代码枚举与 std::error_code 进行比较

c++ - errno 值未更新 (c++)

c++ - QElapsedTimer 可以测量多长时间?

c++ - OpenCV warpPerspective 错误 : Bad number of channels

用于 boost/c++11 的 C++ 包装器

c++ - 创建一个可以在 Visual Studio 2015 中添加引用的属性表

python的re : find words beginning from "string" in any case

sql-server - 基于分隔符的 SQL 拆分,只保留第二个元素