我有如下程序:
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
可以修改,但是ai
循环在只读对象中失败编译为-错误:成员A::i
的赋值。
我知道auto
不检索&
特性,我的问题是:auto
检索c/v限定符和我的情况一样吗?我的测试程序似乎给出了自相矛盾的提示。
发布于 2016-06-09 08:25:34
您在这里复制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'
正如鲍吉拉蒙所建议的那样,下面的代码片段相当于上面的代码:
const int i = 0;
const int& ai = i;
ai = 5;
有关auto
说明符可以在cppreference上找到的更多详细信息。
https://stackoverflow.com/questions/37720323
复制相似问题