C++11 中 std::to_string 的奇怪输出
Strange outputs of std::to_string in C++11
我有一小段C++代码:
#include <array>
#include <string>
#include <iostream>
int main()
{
std::string name = "mario";
std::cerr << "Hello world! " + name + "n";
std::array<float, 4> arr = {12, 12.3, 13, 14};
std::cerr << "first item is: " + std::to_string(arr.front()) << std::endl;
std::cerr << "last item is: " + std::to_string(arr[-1]) << std::endl;
return 0;
}
它编译并输出以下内容:
work ❯ c++ -std=c++11 -o hello_world hello.cpp
work ❯ ./hello_world
Hello world! mario
first item is: 12.000000
last item is: 0.000000
但是,如果我注释掉前两行,例如:
#include <array>
#include <string>
#include <iostream>
int main()
{
//std::string name = "mario";
//std::cerr << "Hello world! " + name + "n";
std::array<float, 4> arr = {12, 12.3, 13, 14};
std::cerr << "first item is: " + std::to_string(arr.front()) << std::endl;
std::cerr << "last item is: " + std::to_string(arr[-1]) << std::endl;
return 0;
}
并编译并运行它。然后它输出以下内容:
work ❯ c++ -std=c++11 -o hello_world hello.cpp
work ❯ ./hello_world
first item is: 12.000000
last item is: 12.000000
我有三个问题:
- 为什么在第一种情况下,当使用
arr[-1]
时,我们会得到 0.000 ? - 为什么在使用
arr[-1]
时,我们在第二种情况下得到 12.000 ? - 为什么在第二种情况下,当我们注释掉前两个语句时,我们会得到不同的
arr[-1]
输出?
编辑:根据评论,我知道arr[-1]
将是未定义的行为,因此在第一种情况下返回 0.000。但是,注释掉其他语句如何改变此行为?这对我来说完全令人困惑,因为我来自 Python 世界。
这是因为未定义的行为,因为std::array::operator[]
不执行任何边界检查,并且您正在访问不存在的内容。
std::array::operator[]
返回对元素的引用 指定位置位置不执行边界检查。
因此,无论您更改或评论什么,UB 仍将是 UB。
相关文章:
- 递归函数计算序列中的平方和(并输出过程)
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 为什么 string::begin() 在即时窗口中输出整个字符串
- 如何将地图<列表<string>、矢量<string>>输出到输出文件?
- 自定义堆栈上 std::string 数据的输出
- 如何使用 rapidjson 读取 json 文件并输出到 std::string?
- 哈希输出为 BYTE 而不是 std::string
- swig perl typemap(out) std::vector<std::string> 在 perl 中不返回所需的输出
- std::string::append(std::string)错误输出
- 使用 std::ostream 方法将格式化文本输出到 std::string 对象
- 如何将 std::string 用于 char* 输出参数
- [swig-JavaScript]是否支持std::vector<std::string>*作为输出?
- 当传入具有std::string成员的结构时,C++-gdb会给出意外的输出
- boost::filesystem::path::string()输出的奇怪行为
- 在布尔矩阵中查找唯一的行(帮助解析std::string的垃圾输出)
- 输出流转换为String或std::ostream
- 在c++类中使用string会输出错误
- Cout在声明一个std::string变量后不给出任何输出
- 如何将<string>具有一定数量单词的向量输出读取到一行?
- 如何分配谷歌协议缓冲区SerializeAsString()输出,其中包含嵌入空到std::string