tôi đã cố gắng để làm một cái gì đó như:Có phải std :: move và std :: copy giống hệt nhau không?
std::copy(std::make_move_iterator(s1.begin()), std::make_move_iterator(s1.end()),
std::make_move_iterator(s2.begin()));
Và nhận lỗi này:
error: using xvalue (rvalue reference) as lvalue
*__result = std::move(*__first);
Mà có vẻ khó hiểu với tôi. Điều tương tự cũng xảy ra nếu bạn sử dụng std::move
. Có vẻ như GCC sử dụng nội bộ một hàm có tên là std::__copy_move_a
di chuyển thay vì bản sao. Việc bạn sử dụng std::copy
hoặc std::move
có quan trọng không?
#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;
}
lý do tại sao bạn tạo trình biến đổi di chuyển từ 's2.begin()'? –