c++ - Is it well-defined to compare with a value-initialized iterator? -
does next programme invoke undefined behavior?
#include <iostream> #include <iterator> int main(int argc, char* argv[]) { (auto = std::istream_iterator<std::string>(std::cin); != std::istream_iterator<std::string>(); ++it) { std::cout << *it << " "; } homecoming 0; }
this 4 year old question says can't compared:
iterators can have singular values not associated container. [example: after declaration of uninitialized pointer x (as int* x;), x must assumed have singular value of pointer. ] results of expressions undefined singular values; excep- tion assignment of non-singular value iterator holds singular value.
but reply says c++14 standard:
however, value-initialized iterators may compared , shall compare equal other value-initialized iterators of same type.
you conflating 2 different issues.
istream_iterator
input iterator, not forwards iterator, c++14 alter cited doesn't apply @ all. allowed compare istream_iterator
s in manner because explicitly specified allow such comparisons. standard says (§24.6.1 [istream.iterator])
the constructor no arguments istream_iterator()
constructs end-of-stream input iterator object, legitimate iterator used end condition. [...]
two end-of-stream iterators equal. end-of-stream iterator not equal non-end-of-stream iterator. 2 non-end-of-stream iterators equal when constructed same stream.
for forwards iterators (which includes bidirectional , random access ones) in general, value-initialized iterators made comparable each other in c++14. if standard library implements it, can compare 2 value-initialized iterators. allows create empty range without underlying container. however, still not allowed compare non-singular iterator value-initialized iterator. next code has undefined behavior in c++14:
std::list<int> l; if(l.begin() == std::list<int>::iterator()) foo(); else bar();
c++ c++11
No comments:
Post a Comment