c++c++14autofunction-declarationreturn-type-deduction

Function declaration with auto using new C++11 syntax but with auto& and without ->


consider the function definition below:

auto& Fnc1() { return someNonLocalVariable; }

Return type is not explicitly specified by -> in this case. But there is the & after auto keyword. Does this guarantee that a reference is returned instead of copy of the variable? Is this a supported language feature (returning reference)? With VS 2017, it works as I expect: Return a reference. But I could not find any online source to verify.


Solution

  • Yes, this is the correct specification, and as Ron commented, became operational in C++14. C++11 did require trailing return type syntax (-> after the parameters).

    See cppreference for more.

    In a function declaration that does not use the trailing return type syntax, the keyword auto indicates that the return type will be deduced from the operand of its return statement using the rules for template argument deduction.

    See also auto type deduction where they include an example using auto&. You can think of this as being the same set of rules for declaring variables using the auto keyword.