Someone told me that I can write
for (iterator it = somecontainer.begin(); it != somecontainer.end(); ++it)
instead of
for (iterator it = somecontainer.begin(); it != somecontainer.end(); it++)
…since the latter one has the cost of an extra unused temporary variable. Is this optimization useful for modern compiler? Do I need to consider this optimization when writing code?
It’s a good habit to get into, since iterators may be arbitrarily complex. For
vector::iteratororintindexes, no, it won’t make a difference.The compiler can never eliminate (elide) the copy because copy elision only eliminates intermediate temporaries, not unused ones. For lightweight objects including most iterators, the compiler can optimize out the code implementing the copy. However, it isn’t always obvious when it can’t. For example, post-incrementing
istream_iterator<string>is guaranteed to copy the laststringobject read. On a non-reference-countedstringimplementation, that will allocate, copy, and immediately free memory. The issue is even more likely to apply to heavier, non-iterator classes supporting post-increment.There is certainly no disadvantage. It seems to have become the predominant style over the past decade or two.