Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it safe to store a reference to an element of a list?

Tags:

c++

list

stl

Is it safe to store a reference to an element in a std::list as long as that element is not removed from the list? I see from this question that it is safe to store list iterators, but is the same true for direct references?

For example

list<int> mylist;
mylist.push_back(3);
int& myint = *mylist.begin();

// modfy mylist

cout << "myint: " << myint << endl;

will myint always be valid as long I don't remove it from the list?

like image 706
David Brown Avatar asked Dec 16 '22 15:12

David Brown


2 Answers

Is it safe to store a reference to an element in a std::list as long as that element is not removed from the list?

Yes. Insertions and erasures do not invalidate references or iterators to elements in a std::list (except, of course, that references and iterators to an erased element is no longer valid).

like image 190
James McNellis Avatar answered Jan 01 '23 08:01

James McNellis


Yes, it's safe. The element won't move, so the reference will only be invalidated in the same circumstances that the iterator would.

like image 24
Tony Delroy Avatar answered Jan 01 '23 10:01

Tony Delroy