微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

应该做你想做的事.

原文地址:https://www.jb51.cc/c/116995.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐