c++vectorstdvectorclang++

std::vector: why out_of_range error doesn't happen?


Mac M1. I learn C++ by Bjarne Stroustrup's book. He show the similar example in his "Programming. Principles and Practice Using C++" book (chapter 5.6.2). Also he writes this exception (out_of_range) is to be occurred.

clang++ --version
Apple clang version 16.0.0 (clang-1600.0.26.4)
Target: arm64-apple-darwin24.0.0
Thread model: posix

My code:

#include <iostream>
#include <vector>

int main(){
    try{
        std::vector<int> items;

        constexpr int size = 5;

        for(int i = 0; i < size; ++i){
            items.push_back(i * 10);
        }

        for(int i = 0; i <= items.size(); ++i){ // out of range!
            std::cout << i << " -> " << items[i] << std::endl;
        }
        std::cout << "Success!" << std::endl;
    }
    catch (std::out_of_range){
        std::cerr << "Range error!" << std::endl;
    }
    catch(...){
        std::cerr << "Something wrong..." << std::endl;
    }
}

Compilation command:

clang++ -std=c++20 main.cpp

Result:

./a.out 
0 -> 0
1 -> 10
2 -> 20
3 -> 30
4 -> 40
5 -> 0
Success!

I've expected to get the out of range exception but it wasn't happened. Why?


Solution

  • I believe you are confusing Bjarne Stroustrup's vector and std::vector.

    Stroustrup's PPPheaders.h uses a #define vector Checked_vector. A Checked_vector changes the behaviour of operator[] to use at instead in PPP_support.h.

    As has already been stated in comments and the other answer, the std::vector does not do bounds checking for operator[]