只移动输入和输出迭代器

move-only input and output iterators

关于 InputIterator/OutputIterator-s 将它们的语义修改为仅移动是否一致?当然,我指的只是新创建的自定义迭代器,而不是 STL

++i++r 表达式的语义要求注释输入和输出迭代器相应地说:

Postcondition: Any copies of the previous value of i are no longer required to be either dereferenceable or to be in the domain of ==.

After this operation r is not required to be incrementable and any copies of the previous value of r are no longer required to be dereferenceable or incrementable.

我认为在大多数情况下禁止拥有 input/output 迭代器副本的可能性更安全,但从未听过这样的建议。这是个坏主意吗?

这可能不是个好主意。迭代器对象通常被设计成轻量级的,并通过值传递以提高效率。许多 C++ 标准库容器都使用按值传递的迭代器。禁用复制构造函数对我来说根本不是一个好主意。

例如,请参阅 http://www.cplusplus.com/reference/vector/vector/vector/ 向量构造函数按值接受输入迭代器。

有关按值接受输出迭代器的 C++ 标准库容器示例,请参阅 http://www.cplusplus.com/reference/algorithm/copy/

Input/OutputIterators 必须先满足 Iterator 要求。这个要求说,从 C++14 开始,[iterator.iterators]、p2:

A type X satisfies the Iterator requirements if:

  • X satisfies the CopyConstructible, CopyAssignable, and Destructible requirements (17.6.3.1)

所以不,它们不能只移动。

在 C++20 中,新的迭代器概念 input_iteratoroutput_iterator 不需要可复制。 ranges 命名空间中的算法以及视图适配器也支持仅移动迭代器。

新视图 ranges::istream_view returns 提高安全性的只移动迭代器。 最后,新的 C++20 view 概念本身不需要可复制性,它只允许移动自己的状态。

仍然可以创建不是 copyablecopyable input_iteratoroutput_iterator,但我建议不要这样做。

forward_iterator当然还是需要copyable。哨兵也需要 copyable

您可以在以下论文中阅读有关设计的矿石