c++ - std::move 和 std::copy 是否相同?

标签 c++ c++11 move-semantics

我尝试做类似的事情:

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 的函数,它 move 而不是复制。使用 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(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);

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

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

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

应该做你想做的。

关于c++ - std::move 和 std::copy 是否相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26432990/

相关文章:

c++ - SQLite - 如何在终端级别和 C++ 应用程序中使用它?

c++ - 使用以 lambda 作为成员的成员初始值设定项列表时出现 VC++ 2013 错误

c++ - 如何在 C++11 中操作日期/日期时间?

c++ - C++中函数返回的值是右值吗?无法使用复制/move 构造函数初始化实例

c++ - 重复使用 move 的容器?

c++ - 我可以调整从中移出的 vector 的大小吗?

c++ - 根据需要 QTableView dosent View 值的模型

c++ - 在 QTabWidget 中动态设置单个选项卡的样式

c++ - 在工厂模式中自动注册派生类

c++ - 我可以在 libleveldb.a 中找到该符号,但是当我创建共享库时,找不到相同的符号。怎么了?