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

Guy*_*ham 2 c++ stl vector c++11

我读了这个教程

std::vector 初学者教程

还看到了这个问题:

类似的问题

然而,当我运行我的简单示例时,我没有看到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;   
}
Run Code Online (Sandbox Code Playgroud)

笔记:

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

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

谢谢,

伙计。

Som*_*ude 5

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

at另一方面,该函数确实具有强制性边界检查,并且将保证抛出out_of_range异常。

这里发生的只是你越界并有未定义的行为

  • 值得注意的是,gcc 的标准库 [* 确实有* 具有边界检查和迭代器跟踪功能的容器的调试版本](/sf/answers/391630991/)。 (2认同)