c – std :: move和std :: copy是否相同?

我尝试过这样的事情:
std::copy(std::make_move_iterator(s1.begin()),std::make_move_iterator(s1.end()),std::make_move_iterator(s2.begin()));

并得到这个错误

error: using xvalue (rvalue reference) as lvalue
        *__result = std::move(*__first);

这让我感到困惑.如果你使用std :: move,会发生同样的事情.似乎GCC内部使用了一个名为std :: __ copy_move_a的函数,它移动而不是复制.是否使用std :: copy或std :: move是否重要?

#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <cstring>

struct Test
{
    typedef std::string::value_type value_type;
    std::string data;

    test()
    {
    }

    Test(const char* data)
        : data(data)
    {
    }

    ~test()
    {
    }

    Test(const Test& other)
        : data(other.data)
    {
        std::cout << "copy constructor.\n";
    }

    Test& operator=(const Test& other)
    {
        data = other.data;
        std::cout << "copy assignment operator.\n";
        return *this;
    }

    Test(Test&& other)
        : data(std::move(other.data))
    {
        std::cout << "Move constructor.\n";
    }

    decltype(data.begin()) begin()
    {
        return data.begin();
    }

    decltype(data.end()) end()
    {
        return data.end();
    }

    void push_back( std::string::value_type ch )
    {
        data.push_back(ch);
    }
};

int main()
{
    Test s1("test");
    Test s2("four");
    std::copy(std::make_move_iterator(s1.begin()),std::make_move_iterator(s2.begin()));
    std::cout << s2.data;
}

解决方法

std :: move(a,b,c);在语义上是相同的
std::copy(std::make_move_iterator(a),std::make_move_iterator(b),c);

你使用它们的努力都失败了,因为第三个参数 – 输出迭代器 – 不应该是移动迭代器.您正在存储到第三个迭代器中,而不是从它移动.都

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

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

应该做你想做的事.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...