我尝试做类似的事情:
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/