C++11 中 std::to_string 的奇怪输出

Strange outputs of std::to_string in C++11

本文关键字:输出 string std to C++11      更新时间:2023-10-16

我有一小段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

我有三个问题:

  1. 为什么在第一种情况下,当使用arr[-1]时,我们会得到 0.000 ?
  2. 为什么在使用arr[-1]时,我们在第二种情况下得到 12.000 ?
  3. 为什么在第二种情况下,当我们注释掉前两个语句时,我们会得到不同的arr[-1]输出?

编辑:根据评论,我知道arr[-1]将是未定义的行为,因此在第一种情况下返回 0.000。但是,注释掉其他语句如何改变此行为?这对我来说完全令人困惑,因为我来自 Python 世界。

这是因为未定义的行为,因为std::array::operator[]不执行任何边界检查,并且您正在访问不存在的内容。

std::array::operator[]返回对元素的引用 指定位置位置不执行边界检查。

因此,无论您更改或评论什么,UB 仍将是 UB。