自动&&变量不是右值引用 [英] auto&& variable's are not rvalue reference
问题描述
为什么要自动&&不是右值引用?
Why auto&& is not rvalue reference?
Widget&& var1 = Widget(); // rvalue reference
auto&& var2 = var1; //var2 not rvalue reference
下面是右值参考示例
void f(Widget&& param); // rvalue reference
Widget&& var1 = Widget(); // rvalue reference
为什么var2不是右值引用,而f和var2是右值引用?
Why var2 is not rvalue reference but f and var2 are rvalue references?
推荐答案
确定了初始化程序的类型后,编译器将使用函数中模板参数推导的规则来确定将替换关键字auto
的类型.调用(有关详细信息,请参见模板参数deduction#Other上下文).关键字auto
可能附带修饰符,例如const
或&
,它们将参与类型推导.
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). The keyword auto
may be accompanied by modifiers, such as const
or &
, which will participate in the type deduction.
例如,给定
const auto& i = expr;
i
的类型恰好是虚构中的参数u
的类型
The type of i
is exactly the type of the argument u
in an imaginary
template template<class U>
void f(const U& u)
如果函数调用f(expr)
已编译.
If the function call f(expr)
was compiled.
通常,可以这样认为.
template template<class U>
void f(paramtype u)
因此,auto&&
可以根据初始化程序推导为左值引用或右值引用.
Therefore, auto&&
may be deduced either as an lvalue reference or rvalue reference according to the initializer.
在您的情况下,假想模板看起来像
In your case , imaginary template would look like
template template<class U>
void f(U&& var2){}
f(var1)
在这里,var1
被命名为rvalue,它被视为lvalue,因此var2
将被推导为lvalue.
Here ,var1
is named rvalue which is being treated as lvalue, so var2
will be deduced as lvalue .
请考虑以下示例:
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&&
这篇关于自动&&变量不是右值引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!