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

Why it does not declare a reference type if 'auto' var is initialized using a function returning reference?

当使用returns引用的函数初始化'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;
}

编辑:link 解释了如何获取参考,但我的问题是此行为的原因

因为那样的话会很烦人。例如,您如何指定您想要推荐信?

当你使用auto的时候,你需要把const&&&volatile放在自己里面。

auto& x = testClass.GetFoo();

是你的解决办法。

C++11 auto 类型推断规则删除引用、const 和 volatile 限定符。 但是,您可以要求 C++ 编译器使用 decltype 类型推断规则来保留所有这些用于声明变量类型的限定符。在您的情况下可能是:

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

但是这段代码会产生一些副作用,比如引用被销毁的对象,所以你需要记住真正的变量类型和生命周期。