C++11:"auto" 关键字是否完全检索 cv 限定符?我有矛盾的样本
C++11: Does "auto" keyword retrieves cv-qualifier at all? I've contradictory sample
我有如下程序:
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循环编译失败——错误:只读对象
中成员A::i
的赋值
我知道 auto
不会检索 &
功能,
我的问题是: auto
是否像我的情况一样检索 c/v 限定符?
我的测试程序似乎给出了矛盾的提示。
您在此处复制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 的建议,下面是与上述代码等效的片段:
const int i = 0;
const int& ai = i;
ai = 5;
有关 auto
说明符 can be found on cppreference 的更多详细信息。
我有如下程序:
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循环编译失败——错误:只读对象
A::i
的赋值
我知道 auto
不会检索 &
功能,
我的问题是: auto
是否像我的情况一样检索 c/v 限定符?
我的测试程序似乎给出了矛盾的提示。
您在此处复制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 的建议,下面是与上述代码等效的片段:
const int i = 0;
const int& ai = i;
ai = 5;
有关 auto
说明符 can be found on cppreference 的更多详细信息。