简体   繁体   English

auto && variable不是右值引用

[英]auto&& variable's are not rvalue reference

Why auto&& is not rvalue reference? 为什么auto &&不是右值参考?

Widget&& var1 = Widget(); // rvalue reference
auto&& var2 = var1; //var2 not rvalue reference

below are rvalue reference example 下面是右值参考示例

void f(Widget&& param); // rvalue reference
Widget&& var1 = Widget(); // rvalue reference

Why var2 is not rvalue reference but f and var2 are rvalue references? 为什么var2不是右值参考,而f和var2是右值参考?

auto&& is a declaration's equivalent of forwarding references (with identical deduction rules). auto&&是声明等同于转发引用(具有相同的扣除规则)。 As such, it will be deduced to an lvalue reference when the initializer is an lvalue. 因此,当初始化器是左值时,它将被推导为左值参考。 However, var is an lvalue (as it is the name of a variable), hence var2 is an lvalue reference. 但是, var是一个左值(因为它是一个变量的名称),因此var2是一个左值引用。

Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call (see template argument deduction#Other contexts for details). 一旦确定了初始化程序的类型,编译器就会使用函数调用中的模板参数推导规则来确定将替换关键字auto的类型(有关详细信息,请参阅模板参数推导#Other contexts)。 The keyword auto may be accompanied by modifiers, such as const or & , which will participate in the type deduction. 关键字auto可以附带修饰符,例如const& ,它们将参与类型推导。

For example, given 例如,给定

const auto& i = expr;

The type of i is exactly the type of the argument u in an imaginary i的类型正是虚构中的参数u的类型

template template<class U> 
void f(const U& u)

If the function call f(expr) was compiled. 如果编译函数调用f(expr)

In general , it can be think as below . 一般来说,可以如下思考。

 template template<class U> 
    void f(paramtype u)

Therefore, auto&& may be deduced either as an lvalue reference or rvalue reference according to the initializer. 因此,根据初始化程序, auto&&可以推导为左值引用或右值引用。

In your case , imaginary template would look like 在您的情况下,虚构的模板看起来像

 template template<class U> 
        void f(U&& var2){}
f(var1) 

Here , var1 is named rvalue which is being treated as lvalue, so var2 will be deduced as lvalue . 这里, var1被命名为rvalue,它被视为左值,因此var2将被推导为左值。

Consider the following examples: 请考虑以下示例:

auto&& var2 = widget() ; //var2 is rvalue reference here .
int x=10;
const int cx=10;
auto&& uref1 = x; // x is int and lvalue, so uref1's type is int&
auto&& uref2 = cx; // cx is const int and lvalue,  so uref2's type is const int&
auto&& uref3 = 27; // 27 is int and rvalue,  so uref3's type is int&&

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM