C++ auto vs auto&

后端 未结 2 1473
不知归路
不知归路 2020-12-03 05:41

if I have a function:

Foo& Bar()
{
   return /// do something to create a non-temp Foo here and return a reference to it
}

why is this:

相关标签:
2条回答
  • 2020-12-03 06:24

    The type deduction for auto works exactly the same as for templates:

    • when you deduce auto you will get a value type.
    • when you deduce auto& you wil get a non-const reference type
    • when you deduce const auto& you will get a const reference
    • when you deduce auto&& you will get
      • a non-const reference if you assign a non-const reference
      • a const reference if you assign a const reference
      • a value when you assign a temporary
    0 讨论(0)
  • 2020-12-03 06:36

    Taken directly from Herb Sutter's blog post:

    auto means “take exactly the type on the right-hand side, but strip off top-level const/volatile and &/&&.”

    0 讨论(0)
提交回复
热议问题