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.)
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…