我試着這樣做: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(s1.end()),
std::make_move_iterator(s2.begin()));
std::cout << s2.data;
}
你爲什麼要從s2.begin()'移動迭代器? – 2014-10-17 20:32:51