为什么在常量引用的自动关键字中忽略const

sam*_*ion 3 c++ auto

int main()
{

    int a = 10;
    const int &b = a;
    int &c = b; //gives error : C should a  reference to a const b 
    auto d = b; // why const is ignored here?
    d = 15;
    cout << a << d;
}
Run Code Online (Sandbox Code Playgroud)

在c ++ Primer中,提到“ 引用类型中的const总是低级的 ”,那么为什么auto d = b不是恒定的呢?

Sto*_*ica 5

因为类型推导规则用于auto推导对象类型。您正在int从引用的副本复制一个新的副本b

那是设计使然。我们要创建新对象而不显式指定它们的类型。通常,它是一个新对象,它是其他对象的副本。如果将其推论为参考,它将无法达到预期的目的。

如果您希望在初始化程序为引用时将推导类型作为引用,则可以使用占位符来实现decltype(auto)

decltype(auto) d = b; // d and b now refer to the same object
d = 15; // And this will error because the cv-qualifiers are the same as b's
Run Code Online (Sandbox Code Playgroud)