Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

c++ - Behaviour of std::list:begin() when list is empty

Does the following give defined results in terms of the C++ standard?

std::list<int> myList;
std::list<int>::iterator myIter = myList.begin();    // any issues?
myList.push_back( 123 );
myIter++;                                  // will myIter point to the 123 I pushed?

I can test this out on the compiler I'm using... but I'd like a more definitive answer.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All standard iterator and container types behave the same in this regard:

§23.2.1 [container.requirements.general] p6

begin() returns an iterator referring to the first element in the container. end() returns an iterator which is the past-the-end value for the container. If the container is empty, then begin() == end();

And table 107 in §24.2.3 [input.iterators] demands that as a precondition for ++it, it shall be dereferenceable, which is not the case for past-the-end iterators (i.e., what you get from end()), as such you're treading into the dreaded domain of undefined behaviour.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...