c++ - 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
我有三个问题:
- 为什么我们在第一种情况下得到 0.000,使用时
arr[-1]
? - 为什么我们在第二种情况下使用时会得到 12.000
arr[-1]
? arr[-1]
当我们注释掉前两个语句时,为什么在第二种情况下会得到不同的输出?
编辑:根据评论,我知道这arr[-1]
将是未定义的行为,因此在第一种情况下返回 0.000。但是,注释掉其他语句如何改变这种行为?因为我来自 Python 世界,所以这让我完全困惑。
解决方案
这是因为未定义的行为,因为std::array::operator[]
不执行任何边界检查,并且您正在访问不存在的东西。
std::array::operator[]
返回对指定位置 pos 的元素的引用。不执行边界检查。
因此,无论您更改或评论什么,UB 仍然是 UB。
推荐阅读
- python - instance.setMetadata() - 没有任何变化
- active-directory - Microsoft Active Directory、OpenLDAP 和 Apache DS 的日期格式不同
- angular - 如何订阅和测试 Observable.of rxjs Angular 9
- python - Python scipy curve_fit 指数方程不符合预期
- java - 如何从 Akka Streams Sink 中抛出的异常中恢复?
- c# - 在 Powershell 中运行时与在 Visual Studio 中运行时的 HttpClient 并发行为不同
- javascript - 将数据传递给反应中的另一个组件
- stackdriver - 自定义指标混淆
- python - 为什么 socket.gethostbyname(socket.gethostname) 只绑定到本地 IP 地址?
- vb.net - Visual Basic HTTP 请求