Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

casting - C++ auto vs auto&

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The type deduction for auto works exactly the same as for templates:

  • 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...