使用新的 C++11 语法的 auto 函数声明,但有 auto& 而没有 ->

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

考虑下面的函数定义:

auto& Fnc1() { return someNonLocalVariable; }
在这种情况下,

Return 类型未由 -> 明确指定。 但是在 auto 关键字之后有 &。 这是否保证返回引用而不是变量的副本? 这是受支持的语言功能(返回参考)吗? 使用 VS 2017,它按我预期的方式工作:Return 参考。 但是我找不到任何在线资源来验证。

是的,这是正确的规范,正如 Ron 评论的那样,在 C++14 中开始运行。 C++11 确实需要尾随 return 类型语法(-> 在参数之后)。

有关更多信息,请参阅 cppreference

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.

另请参阅 auto type deduction,其中包括使用 auto& 的示例。您可以将其视为使用 auto 关键字声明变量的同一组规则。