将局部变量声明为rvalue-reference是否有用,例如T&& r = move(v)? [英] Is it useless to declare a local variable as rvalue-reference, e.g. T&& r = move(v)?
问题描述
你们能在某些情况下给我一个说明性的例子,以证明以下陈述是有用和必要的吗?
Could you guys give me an illustrative example under certain circumstance to prove the following statements are useful and necessary?
AnyTypeMovable v;
AnyTypeMovable&& r = move(v);
推荐答案
否,AnyTypeMovable&& r = move(v);
根本没有用.
考虑以下代码:
#include <iostream>
#include <vector>
class MyMovableType
{
int i;
public:
MyMovableType(int val): i(val){}
MyMovableType(MyMovableType&& r) { this->i = r.i; r.i = -1; }
MyMovableType(const MyMovableType& r){ this->i = r.i; }
int getVal(){ return i; }
};
int main()
{
std::vector<MyMovableType> vec;
MyMovableType a(10);
MyMovableType&& aa = std::move(a);
vec.push_back(aa);
std::cout << a.getVal() << std::endl;
return 0;
}
aa
是l值(如 R. Martinho Fernandes 所述,也由 Xeo -一个命名的rvalue-reference是一个左值),这将打印push_back
调用中),因此您仍然需要将其std::move
移至push_back
方法,在这种情况下:
As aa
is an l-value (as noted by R. Martinho Fernandes, and also by Xeo - a named rvalue-reference is an lvalue), this will print 10
indicating that moving has not been performed (nor in the assignment, nor in the push_back
call), so you still need to std::move
it to the push_back
method, as in this case:
#include <iostream>
#include <vector>
class MyMovableType
{
int i;
public:
MyMovableType(int val): i(val){}
MyMovableType(MyMovableType&& r) { this->i = r.i; r.i = -1; }
MyMovableType(const MyMovableType& r){ this->i = r.i; }
int getVal(){ return i; }
};
int main()
{
std::vector<MyMovableType> vec;
MyMovableType a(10);
MyMovableType&& aa = std::move(a);
vec.push_back(std::move(aa));
std::cout << a.getVal() << std::endl;
return 0;
}
将执行移动,因此打印输出为-1
.因此,尽管实际上您要将aa
传递给push_back
,您仍然需要通过std::move
传递它.
move will be performed, so the printout will be -1
. So, despite the fact that you're passing aa
to the push_back
, you still need to pass it via std::move
.
这篇关于将局部变量声明为rvalue-reference是否有用,例如T&& r = move(v)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!