5

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.

Nitesh
  • 2,681
  • 4
  • 27
  • 45

2 Answers2

5

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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • 1
    plus, it has the same rules as template deduction and that's how they work. – bolov Aug 03 '17 at 10:18
  • @bolov IIRC they're different – Passer By Aug 03 '17 at 10:29
  • @PasserBy except for initializer lists (but they change it with every standard) they are the same https://stackoverflow.com/questions/36652180/what-are-the-type-deduction-rules-for-auto – bolov Aug 03 '17 at 10:41
3

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.

Oleg
  • 205
  • 2
  • 4