【问题标题】:C++11: Does "auto" keyword retrieves cv-qualifier at all? I've contradictory sampleC++11:“auto”关键字是否完全检索 cv 限定符?我有矛盾的样本
【发布时间】:2016-06-09 08:12:59
【问题描述】:

我有如下程序:

struct A{ int i; };

int main()
{
    const int i = 0;
    auto ai = i;
    ai = 2; // OK

    const A buf[2];
    for(auto& a : buf)
    {
        a.i = 1; // error!
    }

    std::cout << buf[0].i << buf[1].i << std::endl;
}

第一个auto ai = i;没有问题,好像auto没有检索到c/v限定符,因为ai可以修改 但是for循环编译失败--error: assignment of member A::i in read-only object

我知道auto 不会检索&amp; 功能, 我的问题是:auto 是否像我的情况一样检索 c/v 限定符? 我的测试程序似乎给出了矛盾的提示。

【问题讨论】:

    标签: c++ c++11 constants auto


    【解决方案1】:

    你在这里复制ai,而不是修改它:

    const int i = 0;
    auto ai = i;
    

    上面的代码相当于:

    const int i = 0;
    int ai = i;
    

    如果您尝试使用非const 引用,您将收到编译时错误:

    const int i = 0;
    auto& ai = i;
    ai = 5; // Error: assignment of read-only reference 'ai'
    

    正如Pau Guillamon 所建议的,这里有一个与上面代码等效的sn-p:

    const int i = 0;
    const int& ai = i;
    ai = 5;
    

    有关auto 说明符can be found on cppreference 的更多详细信息。

    【讨论】:

    • 为了澄清 auto 关键字,我还要补充一点,最后一个代码 sn-p 相当于: const int i = 0;常量 int& ai = i; ai = 5;这显然会导致相同的编译错误。
    • @Hind Forsum:你考虑过接受这个答案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-13
    • 1970-01-01
    • 2017-11-06
    • 1970-01-01
    • 2020-10-04
    相关资源
    最近更新 更多