【问题标题】:auto&& variable's are not rvalue referenceauto&& 变量不是右值引用
【发布时间】:2016-01-20 12:03:07
【问题描述】:

为什么 auto&& 不是右值引用?

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 是右值引用?

【问题讨论】:

  • 我建议阅读this article 转发引用(以前称为通用引用)。
  • 添加auto&& var3 = 10作为右值引用
  • 因为命名的右值引用是左值。
  • “左值引用”和“右值引用”指的是如何绑定引用。绑定后它只是一个引用,除了decltype的结果之外不再有任何区别。请更新您的问题以显示您如何确定“非右值参考”

标签: c++ c++11 auto forwarding-reference


【解决方案1】:

auto&& 是声明的等价转发引用(具有相同的推导规则)。因此,当初始值设定项是左值时,它将被推导出为左值引用。然而,var 是一个左值(因为它是一个变量的名称),因此var2 是一个左值引用。

【讨论】:

    【解决方案2】:

    一旦确定了初始值设定项的类型,编译器就会使用从函数调用中推导模板参数的规则来确定将替换关键字auto 的类型(有关详细信息,请参阅模板参数推导#Other contexts)。关键字auto可以伴随修饰符,如const&,会参与类型推导。

    例如,给定

    const auto& i = expr;
    

    i 的类型正是虚数中的参数u 的类型

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

    如果函数调用 f(expr) 已编译。

    总的来说,可以这样想。

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

    因此,auto&amp;&amp; 可以根据初始化程序推导出为左值引用或右值引用。

    在你的情况下,假想的模板看起来像

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

    这里,var1 被命名为右值,被视为左值,所以var2 将被推导出为左值。

    考虑以下示例:

    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&&
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 2013-08-01
      • 2013-03-23
      • 1970-01-01
      • 1970-01-01
      • 2020-02-16
      相关资源
      最近更新 更多