Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do C++ STL container begin and end functions return iterators by value rather than by constant reference?

As I look at the standard for different STL objects and functions, one thing that doesn't make sense to me is why would the begin() and end() functions for container objects return an iterator by value rather than by constant reference? It seems to me that iterators could be held by the container object internally and adjusted whenever the container is mutated. This would mitigate the cost of creating unnecessary temporaries in for loops like this:

for (std::vector<int>::iterator it=my_vec.begin(); it!=my_vec.end(); ++it){
    //do things
}

Is this a valid concern? Is there something about using references to iterators that makes this a bad idea? Do most compiler implementations optimize this concern away anyway?

like image 522
c.hughes Avatar asked Dec 27 '22 08:12

c.hughes


1 Answers

Iterators are designed to be light-weight and copyable (and assignable). For example, for a vector an iterator might literally just be a pointer. Moreover, the whole point of iterators is to decouple algorithms from containers, and so the container shouldn't have to care at all what kind of iterators anyone else is currently holding

like image 191
Kerrek SB Avatar answered May 10 '23 20:05

Kerrek SB