c++ - 为什么在常量引用的 auto 关键字中忽略 const

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

在c++ Primer中提到“const in reference type is always low-level”那为什么auto d = b不是constant呢?

最佳答案

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

这是设计使然。我们想创建新的对象而不明确指定它们的类型。通常情况下,它是一个新对象,它是其他对象的拷贝。如果将其推导为引用,则会破坏预期目的。

如果您希望推导类型在初始化器是引用时成为引用,则可以使用 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/

相关文章:

c++ - 如何处理 CEdit 控件中的 Return 键?

c++ - 将返回值存储在引用中性能最差吗?

c++ - 模板回调的包装器?

c++ - 如何 SFINAE 启用返回 `auto` 的成员函数

c++ - 在构造函数中指向 this 的弱指针

c++ - 为什么 GCC 不会发生缓冲区溢出?

c++ - C++ 总分

c++ - 为 lambda 分配名称会影响性能吗?

c++ - 如何编写一个完美的缩写函数模板?

c++ - QCustomplot - 隐藏/显示选定的图形