Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it does not declare a reference type if 'auto' var is initialized using a function returning reference?

Tags:

c++

c++11

auto

When an 'auto' var is initialized using a function that returns a reference, why the var type is not a reference? e.g. In following example, why type of x is Foo and not Foo& ?

class TestClass {
public:
    Foo& GetFoo() { return mFoo; }
private:
    Foo mFoo;
};

int main()
{
    TestClass testClass;
    auto x = testClass.GetFoo(); // Why type of x is 'Foo' and not 'Foo&' ?

    return 0;
}

EDIT: The link explains how to get the reference, but my question is the reason for this behavior.

like image 460
Nitesh Avatar asked Aug 03 '17 10:08

Nitesh


People also ask

Can a function return a reference?

Functions can be declared to return a reference type. There are two reasons to make such a declaration: The information being returned is a large enough object that returning a reference is more efficient than returning a copy. The type of the function must be an l-value.

Do references have to be initialized?

References must always be initialized, in the constructor for the class. A class member of reference type must have an initializer provided in all constructors for that class.

Can auto be a reference C++?

Note: auto becomes int type if even an integer reference is assigned to it. To make it reference type, we use auto &. Function that returns a 'reference to int' type : int& fun() {}; m will default to int type instead of int& type : auto m = fun();

What happens when you return a reference C++?

Functions in C++ can return a reference as it's returns a pointer. When function returns a reference it means it returns a implicit pointer.


2 Answers

Because it would be annoying if it worked that way. How, for example, would you specify that you didn't want a reference?

When you use auto, you need to put const, &, &&, and volatile in yourself.

auto& x = testClass.GetFoo();

is your fix.

like image 184
Bathsheba Avatar answered Nov 15 '22 08:11

Bathsheba


C++11 auto type inference rules drop reference, const and volatile qualifiers. However, you may ask C++ compiler to use decltype type inference rules to keep all these qualifiers for declaring variable type. In your case it may be:

decltype(auto) x = testClass.GetFoo();

But this code can cause some side effects like reference to destroyed object, so you need to keep in mind the real variable type and life time.

like image 30
Oleg Avatar answered Nov 15 '22 09:11

Oleg