Home >Backend Development >C++ >Why Does `std::vector`'s `operator[]` Allow Out-of-Bounds Access Without Error?
std::Vector's Access Without Error Despite Out of Bounds
In std::vector, access using operator[] does not trigger error reports, even when an index is out of bounds. This can lead to unexpected results.
Consider the following example:
struct Element { std::vector<double> face; }; int main() { Element elm; // Insert 6 elements into elm.face for (int i = 0; i < 6; i++) elm.face.push_back(i); std::cout << elm.face.size() << std::endl; // Prints 6 std::cout << elm.face[6] << std::endl; // Prints an arbitrary number }
As shown, the vector size is 6, but accessing the nonexistent index elm.face[6] produces a non-error response. This result is undefined behavior, and the value returned can vary depending on platform and memory management.
In contrast, using at() to access elements performs bounds checking and throws an exception (std::out_of_range) when an index is out of bounds. Therefore, it is recommended to use at() instead of operator[] when you require bounds checking.
The above is the detailed content of Why Does `std::vector`'s `operator[]` Allow Out-of-Bounds Access Without Error?. For more information, please follow other related articles on the PHP Chinese website!