Re: list::begin() iterator comportement after push_back operations
On Apr 2, 1:32 pm, Hizo <hizostu...@gmail.com> wrote:
On 2 avr, 13:57, "Bo Persson" <b...@gmb.dk> wrote:
[...]
I thought that in lists, it should not be the case since iterators
are not invalidated when adding elements.
They aren't. When the list is empty, begin() returns the same
iterator as end(), i.e. an iterator which points to one past the
last element. Regardless of what you do after that, that
iterator will point to one past the last element.
I tried this:
-------------------------------------------
#include <iostream>
using std::cout;
using std::endl;
using std::boolalpha;
#include <list>
using std::list;
int main(int argc, char * argv[])
{
list<int> l;
l.push_back(0);
list<int>::const_iterator it = l.begin();
it points to the first element, i.e. the element with 0 in it.
l.pop_back();
This invaliates it, since it removes the element it points to.
l.push_back(1);
l.push_back(2);
cout << *it << endl;
And this is undefined behavior.
cout << boolalpha << (it == l.end()) << endl;
return 0;}
-------------------------------------------
The result (with gcc version 4.3.4 (Gentoo 4.3.4 p1.0, pie-10.1.5))
is:
1
false
(i.e. the expected result)
On what grounds is it expected?
Try compiling with -D_GLIBCXX_CONCEPT_CHECKS -D_GLIBCXX_DEBUG
-D_GLIBCXX_DEBUG_PEDANTIC. (These options really should be the
default, but like most compilers, g++'s defaults are rather
worthless.)
--
James Kanze