如果使用返回引用的函数初始化'auto'var,为什么它不声明引用类型?

Nit*_*esh 5 c++ auto c++11

当使用返回引用的函数初始化'auto'var时,为什么var类型不是引用?例如,在下面的例子中,为什么x的类型是Foo而不是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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:该链接解释了如何获得参考,但我的问题是这种行为的原因.

Bat*_*eba 5

因为如果这样工作就会很烦人.例如,您如何指定您不想要参考?

当你使用auto,你需要把const,&,&&,和volatile自己.

auto& x = testClass.GetFoo();
Run Code Online (Sandbox Code Playgroud)

是你的修复.