`auto` specifier type deduction for references

后端 未结 2 1092
春和景丽
春和景丽 2020-12-03 22:27

Let\'s consider the following code snippet

void Test()
  {
  int x = 0;

  int& rx = x;
  int* px = &x;

  auto apx = px;    // deduced type is int*
         


        
2条回答
  •  情书的邮戳
    2020-12-03 22:47

    Use auto&:

    auto& ref_bigclass = GetBigClass();
    

    References are supposed to be transparent: any operation on them happens on the object they refer to, there is no way to 'get' reference itself.

    UPD: This is covered in 7.1.6.4/6:

    Once the type of a declarator-id has been determined according to 8.3, the type of the declared variable using the declarator-id is determined from the type of its initializer using the rules for template argument deduction.

    And template argument deduction is defined in 14.8.2.1/3:

    If template parameter type P is a reference type, the type referred to by P is used for type deduction.

    P.S. Note that this is different for decltype: decltype(rx) will yield int& type (7.1.6.2/4).

提交回复
热议问题