与值初始化的迭代器进行比较是否定义明确? [英] Is it well-defined to compare with a value-initialized iterator?
问题描述
以下程序是否会调用未定义的行为?
Does the following program invoke undefined behavior?
#include <iostream>
#include <iterator>
int main(int argc, char* argv[])
{
for (auto it = std::istream_iterator<std::string>(std::cin);
it != std::istream_iterator<std::string>();
++it)
{
std::cout << *it << " ";
}
return 0;
}
此 4岁的问题表示无法将它们进行比较:
This 4 year old question says that they can't be compared:
迭代器也可以具有不与之关联的奇异值任何容器.[示例:声明未初始化后指针x(与int * x;一样),必须始终假定x具有一个指针的奇异值.]大多数表达式的结果是未定义为奇异值;唯一的例外是作业非奇异值返回给持有奇异值的迭代器.
Iterators can also have singular values that are not associated with any container. [Example: After the declaration of an uninitialized pointer x (as with int* x;), x must always be assumed to have a singular value of a pointer. ] Results of most expressions are undefined for singular values; the only excep- tion is an assignment of a non-singular value to an iterator that holds a singular value.
但是对于C ++ 14标准,还有另一个答案:
But another answer for says for the C++14 standard:
但是,可以将值初始化的迭代器进行比较,并且应该进行比较等于其他相同类型的值初始化的迭代器.
However, value-initialized iterators may be compared and shall compare equal to other value-initialized iterators of the same type.
推荐答案
您正在混淆两个不同的问题.
You are conflating two different issues.
istream_iterator
是输入迭代器,而不是正向迭代器,因此您引用的C ++ 14更改根本不适用于它.允许您以这种方式比较 istream_iterator
,因为已明确指定它们允许进行这种比较.该标准指出(§24.6.1[istream.iterator])
istream_iterator
is an input iterator, not a forward iterator, so the C++14 change you cited doesn't apply to it at all. You are allowed to compare istream_iterator
s in that manner because they are explicitly specified to allow such comparisons. The standard says that (§24.6.1 [istream.iterator])
不带参数的构造函数
istream_iterator()
始终构造一个流结束输入迭代器对象,这是唯一的用于结束条件的合法迭代器.[...]
The constructor with no arguments
istream_iterator()
always constructs an end-of-stream input iterator object, which is the only legitimate iterator to be used for the end condition. [...]
两个流结束迭代器始终相等.流尾迭代器不等于非流结束迭代器.二当非流结束迭代器由以下项构造时,它们是相等的相同的流.
Two end-of-stream iterators are always equal. An end-of-stream iterator is not equal to a non-end-of-stream iterator. Two non-end-of-stream iterators are equal when they are constructed from the same stream.
通常,对于前向迭代器(还包括双向访问和随机访问的迭代器),在
For forward iterators (which also includes bidirectional and random access ones) in general, value-initialized iterators are made comparable to each other in C++14. If your standard library implements it, then you can compare two value-initialized iterators. This allows you to create an empty range without an underlying container. However, you are still not allowed to compare a non-singular iterator to a value-initialized iterator. The following code has undefined behavior even in C++14:
std::list<int> l;
if(l.begin() == std::list<int>::iterator())
foo();
else
bar();
这篇关于与值初始化的迭代器进行比较是否定义明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!