kma*_*o23 -3 c++ tostring stdstring c++11 stdarray
我有一小段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;
}
Run Code Online (Sandbox Code Playgroud)
它编译并输出以下内容:
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
Run Code Online (Sandbox Code Playgroud)
但是,如果我注释掉前两行,如:
#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;
}
Run Code Online (Sandbox Code Playgroud)
并编译并运行它.然后输出以下内容:
work ? c++ -std=c++11 -o hello_world hello.cpp
work ? ./hello_world
first item is: 12.000000
last item is: 12.000000
Run Code Online (Sandbox Code Playgroud)
我有三个问题:
arr[-1]?arr[-1]?arr[-1]在第二种情况下得到不同的输出,当我们注释掉前两个语句时?编辑:根据评论,我理解这arr[-1]将是未定义的行为,因此在第一种情况下返回0.000.但是,如何评论其他语句会改变这种行为?由于我来自Python世界,这对我来说完全令人困惑.
这是因为未定义的行为,因为std::array::operator[] 不执行任何边界检查,并且您正在访问不存在的内容.
std::array::operator[]返回对指定位置pos处的元素的引用.不执行边界检查.
因此,无论你改变或评论什么,UB仍然是UB.
| 归档时间: |
|
| 查看次数: |
163 次 |
| 最近记录: |