Are const_iterators faster?

后端 未结 11 1884
挽巷
挽巷 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:25

    "Const-ness", like access restriction (public, protected, private), benefits the programmer more than it assists with optimization.
    Compilers can't actually optimize for as many situations involving const as one might think, for many reasons (such as const_cast, mutable data members, pointer/reference aliasing). The most relevant reason here though is that, just because a const_iterator doesn't allow modifying the data it refers to, doesn't mean that that data can't be changed via other means. And if the compiler can't determine that the data is read-only, then it can't really optimize much more than it would for the non-const iterator case.
    More info and examples can be found at: http://www.gotw.ca/gotw/081.htm

提交回复
热议问题