gpt4 book ai didi

c++ - 对于输入迭代器,为什么 a == b 并不意味着++a ==++b?

转载 作者:IT老高 更新时间:2023-10-28 22:36:34 25 4
gpt4 key购买 nike

§24.1.1/3 从 C++03 标准读取,

For input iterators, a == b does not imply ++a == ++b. (Equality does not guarantee the substitution property or referential transparency.) Algorithms on input iterators should never attempt to pass through the same iterator twice. They should be single pass algorithms. Value type T is not required to be an Assignable type (23.1). These algorithms can be used with istreams as the source of the input data through the istream_iterator class.

我无法理解上述引文中的粗体字。谁能帮我理解这个?

另外,以下陈述(上述引文中的斜体文字)是什么意思?它与 a==b++a==++b 表达式有什么关系?

Equality does not guarantee the substitution property or referential transparency.

最佳答案

对于输入迭代器,递增迭代器会使同一迭代器的拷贝无效。

所以:

auto a = istream_iterator<whatever>(something);
auto b = a;
a == b; // true
++a; // b is now invalid
++b; // undefined behavior, I think, but in any case not guaranteed to
// result in anything sensible.

所以当然 ++a ==++b 不能保证。也就是说,a == b 并不意味着 ++a ==++b

我认为“替换属性”的意思是“您对 a 的值所做的任何事情都与对 b 的值做同样的事情的结果相同”,或者类似的 - 它可能会引用各种版本的替换,但有些类似。我认为在这种情况下,它必须意味着“稍后b 做同样的事情”,因为如果 a == b 而我还没有这样做任何无效的东西,那么我使用 ab 中的哪一个都没关系,它们指的是流中的同一点。但是当我增加时,我必须选择一个而失去另一个,因此 ++a ==++b 的困难。

“参照透明”意味着不同的对象是独立的,即它们不是彼此的引用/指针或别名。结合“替代属性”,这意味着:

Later? There is no earlier or later since operations don't have global side-effects. If you can't substitute "later" then you can't substitute

相同序列中的输入迭代器通常引用相同的“实际数据”,例如文件句柄或其他本身包含可变状态的东西。由于 ab 引用相同的文件句柄,并且它们的值取决于其状态,因此您没有引用透明度。这种缺乏是为什么替换失败的原因。

前向迭代器通常引用相同的底层数据(如容器),但只要您以只读方式使用它们(并且不要以其他方式修改容器),它们就不会'不要背叛这个事实,至少在你开始比较它们返回的值的地址之前是这样。因此,它们具有有限的引用透明度它们自己的值,而输入迭代器则没有。它们本身仍然是引用,所以它们引用的东西仍然是别名。

关于c++ - 对于输入迭代器,为什么 a == b 并不意味着++a ==++b?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5947683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com