views:

206

answers:

2

Suppose I have a list, in which no new nodes are added or deleted. However, the nodes may be shuffled around.

Is it safe to save an iterator, pointing to a node in the list, and access it at some arbitrarily later time?

Edit (followup question): The documentation for list::splice() says that it removes elements from the argument list. Does this mean if I call splice, using the same list as arguments to the function, that existing iterators will be invalidated?

+11  A: 

Yes.
The standard grantees that iterators into a list will not be invalidated unless the item, they point at (metaphorically speaking) is removed from the list.

From this page: http://www.sgi.com/tech/stl/List.html

Lists have the important property that insertion and splicing do not
invalidate iterators to list elements, and that even removal invalidates
only the iterators that point to the elements that are removed.
Martin York
A: 

Yes, std::list iterators are just pointers to a node. You can insert, delete (other nodes), and rearrange nodes in the list and the iterator is not invalidated.

James Emerton
There is no guarantee that an iterator is a pointer. In fact you can probably grantee that a std::list<>::iterator is not a pointer as it needs to do intelligent processing for all iterator operations (such as ++)
Martin York