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.
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.