Is it useless to declare a local variable as rvalue-reference, e.g. T&& r = move(v)?

て烟熏妆下的殇ゞ 提交于 2019-12-04 15:20:07

问题


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);

回答1:


No, AnyTypeMovable&& r = move(v); here is not useful at all.

Consider the following code:

#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;

}

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;

}

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.




回答2:


Note that, Named rvalue is lvalue. So you should use std::forward.

#include <iostream>
#include <vector>

class MyMovableType
{
        int i;
public:
        MyMovableType(int val)  noexcept   : i(val){}
        MyMovableType(MyMovableType&& r) noexcept { this->i = r.i; r.i = -1; }
        MyMovableType(const MyMovableType& r) noexcept{ this->i = r.i; }
        int getVal()const noexcept{ return i; }
};

int main()
{
        std::vector<MyMovableType> vec;
        MyMovableType a(10);
        MyMovableType&& aa = std::move(a);

        vec.push_back( std::forward<decltype(a)>(aa) );

        std::cout << a.getVal() << std::endl; // -1 printed.

        return 0;

}


来源:https://stackoverflow.com/questions/18766324/is-it-useless-to-declare-a-local-variable-as-rvalue-reference-e-g-t-r-move

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!