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 compatibility
触发器来编译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&&
时,您将得到- 如果您分配非常量引用,则为非常量引用
- 如果您分配了const引用,则为const引用
- 分配临时值时的值
- 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屋!