首页 > 解决方案 > C++11 中 std::to_string 的奇怪输出

问题描述

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

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

标签: c++c++11tostringstdstringstdarray

解决方案


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

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

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


推荐阅读