Are std::move and std::copy identical?

a 夏天 提交于 2019-12-01 16:17:50

std::move(a, b, c); is semantically identical to

std::copy(std::make_move_iterator(a),
          std::make_move_iterator(b),
          c);

Your efforts to use them both failed because the third argument - the output iterator - should not be a move iterator. You are storing into the third iterator, not moving from it. Both

std::copy(std::make_move_iterator(s1.begin()),
          std::make_move_iterator(s1.end()),
          s2.begin());

and

std::move(s1.begin(), s1.end(), s2.begin());

should do what you want.

std::move moves the elements if possible, and copies otherwise. std::copy will always copy.

libstdc++'s copy_move_a also takes a template parameter _IsMove. That, and the iterator types, it delegates to a __copy_move class template that is partially specialized for different iterator categories, etc. but most importantly: Whether to move or not. One of the specializations is

#if __cplusplus >= 201103L
  template<typename _Category>
    struct __copy_move<true, false, _Category>
    // first specialized template argument is whether to move
    {
      template<typename _II, typename _OI>
        static _OI
        __copy_m(_II __first, _II __last, _OI __result)
        {
      for (; __first != __last; ++__result, ++__first)
        *__result = std::move(*__first); // That may be your line
      return __result;
    }
    };
#endif

Your code fails to compile for a completely different reason: The second range is given through move_iterators. If you dereference them, they return an rvalue reference to the object - and you can't assign something to an xvalue of scalar type.

int i;
std::move(i) = 7; // "expression not assignable" -- basically what your code does

The std::move is implicitly included in *__result and is of the same value category, that is, an xvalue.

For your example,

std::copy(std::make_move_iterator(s1.begin()), std::make_move_iterator(s1.end()),
          s2.begin());

should work fine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!