Sunday, October 17, 2010


Assume that i is an iterator to a container.
 Are the following two lines functionally equivalent?
   func(i); ++i;
An example would be if func was the erase function on a container. In the first case the iterator would still be valid after the function call. In the second case, the iterator would be invalid after the function call. Care in not invalidating the iterator is needed when erasing items from a container. Expressions like func(i++) are part of the idiom to erase items correctly. Here is an example: myMap.erase(i++) does not invalidate the iterator, i. Doing myMap.erase(i) in a loop is popular source of program crashes.

Reference: More Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions by Herb Sutter. Addison-Wesley, 2001, p. 59.

No comments:

Post a Comment