use*_*097 8 c++ move-semantics c++11
我尝试过这样的事情:
std::copy(std::make_move_iterator(s1.begin()), std::make_move_iterator(s1.end()),
std::make_move_iterator(s2.begin()));
Run Code Online (Sandbox Code Playgroud)
并得到这个错误:
error: using xvalue (rvalue reference) as lvalue
*__result = std::move(*__first);
Run Code Online (Sandbox Code Playgroud)
这让我感到困惑.如果你使用同样的事情发生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;
}
Run Code Online (Sandbox Code Playgroud)
Cas*_*sey 18
std::move(a, b, c); 在语义上是相同的
std::copy(std::make_move_iterator(a),
std::make_move_iterator(b),
c);
Run Code Online (Sandbox Code Playgroud)
你使用它们的努力都失败了,因为第三个参数 - 输出迭代器 - 不应该是移动迭代器.您正在存储到第三个迭代器中,而不是从它移动.都
std::copy(std::make_move_iterator(s1.begin()),
std::make_move_iterator(s1.end()),
s2.begin());
Run Code Online (Sandbox Code Playgroud)
和
std::move(s1.begin(), s1.end(), s2.begin());
Run Code Online (Sandbox Code Playgroud)
应该做你想做的事.
std::move如果可能,移动元素,否则复制.std::copy将永远复制.
libstdc ++ copy_move_a也有一个模板参数_IsMove.它和迭代器类型一起委托给一个__copy_move类模板,该模板部分专用于不同的迭代器类别等,但最重要的是:是否move存在.其中一个专业是
#if __cplusplus >= 201103L
template<typename _Category>
struct __copy_move<true, false, _Category>
// first specialized template argument is whether to move
{
template<typename _II, typename _OI>
static _OI
__copy_m(_II __first, _II __last, _OI __result)
{
for (; __first != __last; ++__result, ++__first)
*__result = std::move(*__first); // That may be your line
return __result;
}
};
#endif
Run Code Online (Sandbox Code Playgroud)
您的代码编译失败的原因完全不同:第二个范围是通过move_iterators 给出的.如果取消引用他们,他们返回一个右值参考对象-你不能分配东西标量型的x值.
int i;
std::move(i) = 7; // "expression not assignable" -- basically what your code does
Run Code Online (Sandbox Code Playgroud)
将std::move被隐式包括在*__result和是相同的值的类别,即,x值的.
以你为例,
std::copy(std::make_move_iterator(s1.begin()), std::make_move_iterator(s1.end()),
s2.begin());
Run Code Online (Sandbox Code Playgroud)
应该工作正常.
| 归档时间: |
|
| 查看次数: |
3886 次 |
| 最近记录: |