问题
if I have a function:
Foo& Bar()
{
return /// do something to create a non-temp Foo here and return a reference to it
}
why is this:
auto x = Bar(); /// probably calls copy ctor - haven't checked
not the same as this?
auto &x = Bar(); /// actually get a reference here
(Actually, I'd expect the second version to get a reference to a reference, which makes little sense.)
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.
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.)
(Second use of time machine will be making C++ pass by reference by default. With a #pragma compatibility trigger for compiling C code. ARGH.)
回答1:
The type deduction for auto works exactly the same as for templates:
- when you deduce
autoyou 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
回答2:
Taken directly from Herb Sutter's blog post:
auto means “take exactly the type on the right-hand side, but strip off top-level const/volatile and &/&&.”
来源:https://stackoverflow.com/questions/20832862/c-auto-vs-auto