Can't bind lvalue to rvalue reference

匆匆过客 提交于 2019-12-19 06:40:10

问题


I have this C++ test code snippet,

#include <vector>

class A {
        std::vector<int> x;
public:
        A(std::vector<int>&& _x) : x(_x) {}
};

class B {
        A a;
public:
        B(std::vector<int>&& _x) : a(/*move(*/_x/*)*/) {}
};

I'm passing _x to B as rvalue reference, but it's getting converted to lvalue when passed into A's constructor and I have to use std::move() to make it work. My question is why _x is lvalue and not an rvalue reference in a()?


回答1:


Quote from WIKI

For safety reasons, some restrictions are imposed. A named variable will never be considered to be an rvalue even if it is declared as such. To get an rvalue, the function template std::move() should be used. Rvalue references can also be modified only under certain circumstances, being intended to be used primarily with move constructors.




回答2:


Anything that has a name is an lvalue reference. You have to use std::move on parameters to pass them on as rvalue references.



来源:https://stackoverflow.com/questions/40350029/cant-bind-lvalue-to-rvalue-reference

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