I am planning to use std::list in my code, I decided not to use std::forward_list, because for deletions (I figured) the whole list will have to traversed, O(N) complexity f
For lists, an iterator is valid even if other items in the list are erased. It becomes garbage when that item the iterator references in the list is removed.
So, as long as you know the iterator you're passing around isn't being removed by some other piece of code, they're safe to hold onto. This seems fragile though.
Even if there was a construct outside of iterators to reference a node in the list, it would suffer from the same fragility.
However, you can have each node contain an std::shared_ptr
to the data it stores instead of the object itself and then pass around std::weak_ptr
's to those objects and check for expired
before accessing those weak_ptr
's.
eg
instead of
std::list foo;
you would have
std::list> foo;
have a look here for info on weak_ptr
's