考虑下面的函数定义:
auto& Fnc1() { return someNonLocalVariable; }
在这种情况下,-> 没有明确指定返回类型。 但是在 auto 关键字之后有 &。 这是否保证返回引用而不是变量的拷贝? 这是受支持的语言功能(返回引用)吗? 使用 VS 2017,它按我预期的方式工作:返回引用。 但是我找不到任何在线资源来验证。
最佳答案
是的,这是正确的规范,正如 Ron 评论的那样,在 C++14 中开始运行。 C++11 确实需要尾随返回类型语法(->
在参数之后)。
参见 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
关键字声明变量的同一组规则。
关于c++ - 使用新的 C++11 语法的 auto 函数声明,但有 auto& 而没有 ->,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53998710/