samedi 31 janvier 2015

Why C++ STL vector does not go out of range


I have this code and I am wondering how it works; Why does it allow me to access an element using a value larger than the size of the vector using the operator[]?


But then when I use the at() function which does bounds checking, it throws the proper error.


I read that the behavior of doing this is undefined, but I am curious: Why does operator[] work for out of range element access?



// 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);




Aucun commentaire:

Enregistrer un commentaire