Should I prefer iterators over const_iterators?

前端 未结 6 2170
没有蜡笔的小新
没有蜡笔的小新 2020-12-14 16:07

Someone here recently brought up the article from Scott Meyers that says:

  • Prefer iterators over const_iterators (pdf link).
6条回答
  •  清歌不尽
    2020-12-14 16:58

    I generally prefer constness, but recently came across a conundrum with const_iterators that has confused my "always use const were possible" philosophy:

    MyList::const_iterator find( const MyList & list, int identifier )
    {
        // do some stuff to find identifier
        return retConstItor;
    }
    

    Since passing in a const list reference required that I only use const iterators, now if I use the find, I cannot do anything with the result but look at it even though all I wanted to do was express that find would not change the list being passed in.

    I wonder perhaps, then, if Scott Mayers advice has to do with issues like this where it becomes impossible to escape const-ness. From what I understand, you cannot (reliably) un-const const_iterators with a simple cast because of some internal details. This also (perhaps in conjunction) be the issue.

    this is probably relevant: How to remove constness of const_iterator?

提交回复
热议问题