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

天涯浪子 提交于 2019-12-13 14:21:16

问题


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?


回答1:


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




回答2:


If the begin and end methods returned a reference, the container would be forced to have each of those iterators as members. The standards people try to leave as much flexibility to an implementation as possible.

For example you can create a simple wrapper for an array that behaves as a standard container and doesn't consume any extra memory. If this wrapper were required to contain the iterators it wouldn't be so simple or small anymore.




回答3:


Well, if you choose right iterator, STL would :-)

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

Iterator in STL has pointer-semantic. Const iterator has const pointer semantic.



来源:https://stackoverflow.com/questions/15097778/why-do-c-stl-container-begin-and-end-functions-return-iterators-by-value-rathe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!