Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::list<>::splice invalidates iterators. Rationale?

I wonder what is the rationale behind making std::list<>::splice to invalidate the iterators that refer to the subsequence being spliced into the new container. This looks kinda illogical to me, especially in light of standard std::container::swap specification. According to the language standard std::container::swap does not invalidate any iterators. This is a perfectly reasonable practical specification. However, I'd say that std::list<>::splice would also benefit greatly from iterator-preserving behavior.

I understand that there might be some purely academic considerations based on the concepts of iterator reachability, etc. But at the same time splice is a std::list-specific operation, meaning that providing a custom-tailored specification for it probably would not make a serious conceptual damage to the STL design in general.

So what was it? Would it outlaw or overcomplicate some practical implementations of std::list, which I fail to recognize?

like image 299
AnT Avatar asked Jul 05 '12 21:07

AnT


People also ask

Why are iterators invalidated?

All iterators and the references are invalidated if the inserted item is not inserted at the end of the deque. If the items are deleted from any of the position except the end position, then all iterators will be invalidated. Same as like insert or erase.

How can we avoid iterator invalidation?

You could avoid moving elements of the container by maintaining a free-list (see http://www.memorymanagement.org/glossary/f.html#free.list). To avoid invalidation of references to elements you can use a std::deque if you do not insert or erase in the middle. To avoid invalidation of iterators you can use a std::list.

Does std :: move invalidate iterators?

No, they should not get invalidated after a move operation.

Should I use std :: list?

Consider using std::list if: You need to store many items but the number is unknown. You need to insert or remove new elements from any position in the sequence. You do not need efficient access to random elements.


2 Answers

In C++11 splice does not invalidate the iterators, but make them refer to the appropriate elements in the *this container. This is all described in 23.3.5.5.

like image 74
David Rodríguez - dribeas Avatar answered Oct 08 '22 22:10

David Rodríguez - dribeas


If the containers have customised, unequal (non compatible) allocators, you cannot swap pointers, you have no choice but to really copy elements around.

like image 39
curiousguy Avatar answered Oct 08 '22 22:10

curiousguy