为什么C++ STL向量不会超出范围

nod*_*ase 0 c++ stl data-structures

我有这个代码,我想知道它是如何工作的; 为什么它允许我使用大于使用operator[]?的向量大小的值来访问元素?

但是当我使用at()边界检查的函数时,它会抛出正确的错误.

我读到这样做的行为是undefined,但我很好奇:为什么operator[]超出范围元素访问工作?

// vector of length 3
std::vector<int> adj(3);

// output: 3
printf("Size of adj is %lu\n", adj.size());

// assign using index that is larger than vector size, e.g., 12
adj[12] = 314159;

// succeeds, output: 314159
printf("adj[12] is %d", adj[12]);

// fails, throws out_of_range
adj.at(12);
Run Code Online (Sandbox Code Playgroud)

rat*_*eak 9

出于速度原因,不检查越界.假设程序员在使用operator []之前知道他在边界内.

同样未定义的行为可能导致任何事情从预期的行为发生,到崩溃到门洞到你的鼻腔开放.