c++ - std::move 两个双端队列 - 输入与输出迭代器

标签 c++ c++11 iterator std move

看看下面的代码:

#include <algorithm>
#include <deque>
#include <iostream>

using namespace std;

int main()
{
  deque<int> in {1,2,3};
  deque<int> out;
  // line in question
  move(in.begin(), in.end(), out.begin());
  for(auto i : out)
    cout << i << endl;

  return 0;
}

这不会 move 任何东西。查看示例 here , 必须这样写有问题的行:

move(in.begin(), in.end(), std::back_inserter(out));

这在某种程度上是有道理的,因为 std::move 期望它的前两个参数是 InputInterator(此处满足),第三个参数是 OutputIterator(out.begin() 不是)。

如果执行原始代码并且向 move 传递一个不是 OutputIterator 的迭代器,实际会发生什么?为什么 C++ 的类型安全在这里不起作用?为什么将输出迭代器的构造委托(delegate)给外部函数,即为什么 out.backInserter() 不存在?

最佳答案

原始代码尝试取消引用并递增 out.begin()。由于 out 是空的,这是一个尾后迭代器,它不能被取消引用或递增。这样做会产生未定义的行为。

std::move expects [...] the third one to be an OutputIterator (which out.begin() is not).

是的。具体来说,它是一个可变的随机访问迭代器,它支持输出迭代器所需的所有操作,等等。

What does actually happen if the original code is executed and move is passed an iterator that is not an OutputIterator?

如果迭代器不支持函数所需的输出迭代器所需的操作,则会导致编译错误;或未定义的行为,如果操作存在但做了输出迭代器所需的操作以外的事情。

Why does C++'s type-safety not work here?

因为类型是正确的。静态类型系统无法检测到不正确的运行时状态(作为尾后迭代器,而不是元素至少与输入范围一样多的序列的开始)。

why does out.backInserter() not exist?

这必须为所有序列容器单独编写:标准容器和您自己定义的任何其他容器。通用函数只需在标准库中实现一次,即可用于任何支持 push_back 的容器。

关于c++ - std::move 两个双端队列 - 输入与输出迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27361692/

相关文章:

c++ - 右值引用成员变量有什么用

c++ - 如何实现从C++函数到Swift的回调

c++ - std:map 与 operator= 不匹配

c++ - 迭代集合并集的简洁方法?

C++:将 char * 转换为 wstring

c++ - 具有左值和右值的可变参数模板类构造函数

c++ - 如何使用 auto 获得 const_iterator?

c++ - static constexpr 成员的统一初始化

c++ - 错误 : vector iterators incompatible

C++ 返回多个项目