Are const_iterators faster?

后端 未结 11 1870
挽巷
挽巷 2020-11-30 02:04

Our coding guidelines prefer const_iterator, because they are a little faster compared to a normal iterator. It seems like the compiler optimizes t

11条回答
  •  天命终不由人
    2020-11-30 02:26

    They are for non-trivial containers/iterators. Get your habits straight and you won't lose performance when it does matter.

    Also, there are several reasons to prefer const_iterator, no matter what:

    1. Use of const expresses code intent (i.e. reading only, no mutating of these objects).
    2. Use of const(_iterator) prevents accidental modification of data. (see above)
    3. Some libraries use lack-of-const begin() to flag data as dirty (i.e. OpenSG) and will send it to other threads/over-network on sync, so there it has real performance implications.
    4. Also, allowing you to access non-const member functions could have side-effects that you don't intend (in much the same way as above), for instance detaching copy-on-write containers from shared data. Qt for one, does exactly that.

    As an example of the last point above, here's an excerpt from qmap.h in Qt:

    inline iterator begin() { detach(); return iterator(e->forward[0]); }
    inline const_iterator begin() const { return const_iterator(e->forward[0]); }
    

    Even if iterator and const_iterator are practically equivalent (except for the const), detach() creates a new copy of the data if there are two or more objects using it. This is completely useless if you're just going to read the data, which you indicate by using const_iterator.

    Of course, there are data points in the other direction:

    1. For STL containers and and many simple-copy-semantic containers it won't matter for performance. The code is equivalent. However, the able to write clear code and avoid bugs wins out.
    2. Const is viral, so if you're working in a legacy code base where const is poorly (or simply not) implemented, you might have to work with non-const iterators.
    3. Apparently, some pre C++0x STL has a bug where const_iterators couldn't be used to erase() elements from containers.

提交回复
热议问题