std :: move和std :: copy是否相同? [英] Are std::move and std::copy identical?

查看:250
本文介绍了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都重要吗?

Which seemed confusing to me. The same thing happens if you use std::move. It appears that GCC internally uses a function called std::__copy_move_a which moves rather than copies. Does it matter whether you use std::copy or 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(s1.end()), 
              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);

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

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());

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

应该做你想做的事.

这篇关于std :: move和std :: copy是否相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆