无法将左值绑定到右值引用 [英] Can't bind lvalue to rvalue reference

查看:123
本文介绍了无法将左值绑定到右值引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个C ++测试代码段

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/*)*/) {}
};

我正在将 _x 传递给B作为右值引用,但是当传递到 A 的构造函数中时,它已转换为左值,我必须使用 std:: move()使其起作用.我的问题是为什么_x是而不是 a()中的右值引用?

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()?

推荐答案

维基百科

出于安全原因,施加了一些限制.命名变量即使声明为右值,也永远不会被视为右值.要获取右值,应使用函数模板std :: move().右值引用也只能在某些情况下进行修改,主要是与move构造函数一起使用.

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.

这篇关于无法将左值绑定到右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆