Why doesn't it declare a reference type if "auto" var is initialized with a function that returns a link?

When "auto" var is initialized with a function that returns a link, why is the var type not a reference? For example, in the following example, why type 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 link, but my question is the reason for this behavior.

+5
source share
2 answers

Because it would be unpleasant if it worked. How, for example, would you indicate that you do not need a link?

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

 auto& x = testClass.GetFoo(); 

- this is your correction.

+5
source

C ++ 11 auto type withdrawal of inference rules, constants and volatile determinants. However, you can ask the C ++ compiler to use decltype type inference rules to preserve all of these qualifiers for declaring a variable type. In your case, it could be:

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

But this code can cause some side effects, such as a reference to the destroyed object, so you need to keep in mind the actual type of the variable and the lifetime.

+2
source

Source: https://habr.com/ru/post/1270530/


All Articles