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.)
Software Engineering C Auto is a storage class/ keyword in C Programming language which is used to declare a local variable. A local variable is a variable which is accessed only within a function, memory is allocated to the variable automatically on entering the function and is freed on leaving the function.
C++11 introduces the keyword auto as a new type specifier. auto acts as a placeholder for a type to be deduced from the initializer expression of a variable. With auto type deduction enabled, you no longer need to specify a type while declaring a variable.
The auto keyword is a simple way to declare a variable that has a complicated type. For example, you can use auto to declare a variable where the initialization expression involves templates, pointers to functions, or pointers to members.
1) A static int variable remains in memory while the program is running. A normal or auto variable is destroyed when a function call where the variable was declared is over. For example, we can use static int to count a number of times a function is called, but an auto variable can't be used for this purpose.
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 &/&&.”
The type deduction for auto
works exactly the same as for templates:
auto
you will get a value type.auto&
you wil get a non-const reference typeconst auto&
you will get a const referenceauto&&
you will get
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With