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;
}

c++ Primer 中提到“引用类型中的 const 总是低级的 ” 那么 auto d = b 怎么不是常量呢?

最佳答案

因为 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

关于c++ - 为什么在常量引用的 auto 关键字中忽略 const,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46091883/

10-12 21:37
查看更多