C++ 自动与自动& [英] C++ auto vs auto&
问题描述
如果我有一个函数:
Foo& Bar()
{
return /// do something to create a non-temp Foo here and return a reference to it
}
这是为什么:
auto x = Bar(); /// probably calls copy ctor - haven't checked
和这个不一样?
auto &x = Bar(); /// actually get a reference here
(实际上,我希望第二个版本能够获得对参考的引用,这没什么意义.)
如果我将 x
的类型明确指定为值或引用,我将得到我所期望的(当然).不过,我希望 auto
会编译为 Bar()
的返回类型,在这种情况下,它是一个引用.
If I explicitly specified the type of x
as a value or a reference, I'll get what I expect (of course). I would expect, though, that auto
would compile to the return type of Bar()
, which, in this case, is a reference.
Foo
和 Foo&
之间是否存在隐式转换?
Is there an implicit cast between Foo
and Foo&
that comes into play here?
(接受规范参考,但我已经厌倦了阅读委员会的发言.)
(Spec references accepted, though I'm getting tired of reading committee-speak.)
(第二次使用时间机器将默认通过引用使 C++ 传递.使用 #pragma compatible
触发器来编译 C 代码.ARGH.)
(Second use of time machine will be making C++ pass by reference by default. With a #pragma compatibility
trigger for compiling C code. ARGH.)
推荐答案
auto
的类型推导与模板的工作方式完全相同:
The type deduction for auto
works exactly the same as for templates:
- 当你推导
auto
时,你会得到一个值类型. - 当你推导
auto&
时,你会得到一个非常量引用类型 - 当你推导
const auto&
时,你会得到一个const引用 - 当你推导出
auto&&
你会得到- 如果您分配非常量引用,则为非常量引用
- 常量引用,如果你分配一个常量引用
- 分配临时值时的值
- 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
这篇关于C++ 自动与自动&的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!