Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::list<>: Element before l.begin()

Tags:

c++

list

Short question: Is the following code unsafe using other compilers than I do (mingw32), or is it valid to use?

list<int> l;
/* add elements */
list<int>::iterator i = l.begin();
i--;
i++;
cout << *i << endl;

...or in other words: is i defined to point to l.begin() after this?

like image 206
shraddr Avatar asked Dec 10 '22 06:12

shraddr


2 Answers

Yes, the code is unsafe. Once you attempt to move before begin() you have caused undefined behavior. Attempting to move "back again" may not work.

like image 165
CB Bailey Avatar answered Dec 26 '22 16:12

CB Bailey


A std::list traverses its contents via linked list pointers, so pointer arithmetic is not used to calculate a correct position. The previous position from .begin() will have no data and shouldn't provide any valid traversal mechanisms.

Containers like std::vector have random access iterators and would use pointer arithmetic under the covers, so they would probably give the right result (no problem), but its still a bad idea.

So, it shouldn't work, its undefined, and don't do it even if it does work somehow :)

like image 34
John Humphreys Avatar answered Dec 26 '22 18:12

John Humphreys