访问未初始化的元素时,std向量不会抛出out_of_range异常[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

我读了这个教程

std::vector beginners tutorial

并且还看到了这个问题:

similar tpoic question

然而,当我运行我的简单示例时,我没有看到预期的结果,这是 - >没有抛出qazxsw poi异常。

我在这里误解了什么吗?

我运行的示例代码如下(代码运行并成功终止,即 - 没有抛出异常):

std::out_of_range

笔记:

示例代码使用-std = c ++ 11选项进行编译。

编译器版本是g ++ 5.4(在我的Ubuntu 16.04机器上)。

谢谢,

盖伊。

c++ c++11 vector stl
2个回答
3
投票

向量#include <iostream> #include <vector> using namespace std; class MyObjNoDefualtCtor { public: MyObjNoDefualtCtor(int a) : m_a(a) { cout << "MyObjNoDefualtCtor::MyObjNoDefualtCtor - setting m_a to:" << m_a << endl; } MyObjNoDefualtCtor(const MyObjNoDefualtCtor& other) : m_a(other.m_a) { cout << "MyObjNoDefualtCtor::copy_ctor - setting m_a to:" << m_a << endl; } ~MyObjNoDefualtCtor() { cout << "MyObjNoDefualtCtor::~MyObjNoDefualtCtor - address is" << this << endl; } // just to be sure - explicitly disable the defualt ctor MyObjNoDefualtCtor() = delete; int m_a; }; int main(int argc, char** argv) { // create a vector and reserve 10 int's for it // NOTE: no insertion (of any type) has been made into the vector. vector<int> vec1; vec1.reserve(10); // try to access the first element - due to the fact that I did not inserted NOT even a single // element to the vector, I would except here an exception to be thrown. size_t index = 0; cout << "vec1[" << index << "]:" << vec1[index] << endl; // now try to access the last element - here as well: due to the fact that I did not inserted NOT even a single // element to the vector, I would excpet here an excpetion to be thrown. index = 9; cout << "vec1[" << index << "]:" << vec1[index] << endl; // same thing goes for user defined type (MyObjNoDefualtCtor) as well vector<MyObjNoDefualtCtor> vec2; vec2.reserve(10); // try to access the first element - due to the fact that I did not inserted NOT even a single // element to the vector, I would except here an exception to be thrown. index = 0; cout << "vec2[" << index << "]:" << vec2[index].m_a << endl; // now try to access the last element - here as well: due to the fact that I did not inserted NOT even a single // element to the vector, I would except here an exception to be thrown. index = 9; cout << "vec2[" << index << "]:" << vec2[index].m_a << endl; return 0; } 函数可能会也可能不会进行边界检查。具有边界检查的实现通常仅用于调试构建。 GCC及其标准库没有。

另一方面,operator[]函数确实有强制边界检查,并将保证抛出at异常。

这里发生的事情只是你走出界限并拥有out_of_range


1
投票

undefined behavior执行范围检查,而不是(必然)at()

您的代码具有未定义的行为。

如果您想确保获得例外,请使用

operator[]

代替

vec1.at(index)
© www.soinside.com 2019 - 2024. All rights reserved.