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.
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.
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.
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();
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.
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.
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.
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