Is it safe to store a reference to an element of a list?
Is it safe to store a reference to an element in a std::list开发者_JAVA百科
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?
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).
Yes, it's safe. The element won't move, so the reference will only be invalidated in the same circumstances that the iterator would.
精彩评论