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

时间:2018-01-01 19:40:15

标签: c++ c++11 vector stl

我读了这个教程

std::vector beginners tutorial

并且还看到了这个问题:

similar tpoic question

然而,当我运行我的简单示例时,我没有看到例外结果,即 - >不会抛出std::out_of_range异常。

我在这里误解了什么吗?

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

#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;   
}

注意:

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

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

谢谢,

盖。

2 个答案:

答案 0 :(得分:3)

向量operator[]函数可能会也可能不会进行边界检查。具有边界检查的实现通常仅用于调试构建。 GCC及其标准库没有。

另一方面,at函数具有强制边界检查功能,并且保证会抛出out_of_range异常。

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

答案 1 :(得分:1)

执行范围检查的是at(),而不是(必须)operator[]

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

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

vec1.at(index)

而不是

vec1[index]