Please take a look at the following simple code:
class Foo
{
public:
Foo(){}
~Foo(){}
Foo(const Foo&){}
Foo& operator=(const Foo&) { return *this; }
};
static Foo g_temp;
const Foo& GetFoo() { return g_temp; }
I tried to use auto
like this:
auto my_foo = GetFoo();
I expected that my_foo
will be a constant reference to Foo
, which is the return type of the function. However, the type of auto
is Foo
, not the reference. Furthermore, my_foo
is created by copying g_temp
. This behavior isn't that obvious to me.
In order to get the reference to Foo
, I needed to write like this:
const auto& my_foo2 = GetFoo();
auto& my_foo3 = GetFoo();
Question: Why does auto
deduce the return type of GetFoo
as an object, not a reference?
Read this article: Appearing and Disappearing consts in C++
Since you can retain the cv-qualifier if the type is a reference or pointer, you can do:
Instead of having to specify it as
const
(same goes forvolatile
).Edit: As for why
auto
deduces the return type ofGetFoo()
as a value instead of a reference (which was your main question, sorry), consider this:The above will create a copy, since
my_foo
is a value. Ifauto
were to return an lvalue reference, the above wouldn't be possible.