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

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了访问未初始化的元素时,std向量不会抛出out_of_range异常[重复]相关的知识,希望对你有一定的参考价值。

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

我读了这个教程

std::vector beginners tutorial

并且还看到了这个问题:

similar tpoic question

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

我在这里误解了什么吗?

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

std::out_of_range

笔记:

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

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

谢谢,

盖伊。

答案

向量#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

另一答案

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

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

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

operator[]

代替

vec1.at(index)

以上是关于访问未初始化的元素时,std向量不会抛出out_of_range异常[重复]的主要内容,如果未能解决你的问题,请参考以下文章

C++ - 使用 std::sort 对结构向量进行排序导致读取访问冲突

std::vector 段错误而不是抛出异常

向量中类元素的初始化

两个 std::vectors 之间的匹配元素

构造函数中的引用向量:未初始化的引用

用向量的向量的元素初始化向量的空向量