Hin*_*sum 5 c++ const auto c++11
我有以下程序:
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;
}
Run Code Online (Sandbox Code Playgroud)
第一个auto ai = i;没有问题,似乎auto没有检索c/v限定符,因为ai可以修改但for循环失败编译为 - 错误:A::i在只读对象中分配成员
我知道这auto不会检索&功能,我的问题是:auto在我的情况下检索c/v限定符吗?我的测试程序似乎给出了相互矛盾的提示.
Vit*_*meo 12
你在ai这里复制,而不是修改它:
const int i = 0;
auto ai = i;
Run Code Online (Sandbox Code Playgroud)
上面的代码相当于:
const int i = 0;
int ai = i;
Run Code Online (Sandbox Code Playgroud)
如果您尝试进行非const引用,则会出现编译时错误:
const int i = 0;
auto& ai = i;
ai = 5; // Error: assignment of read-only reference 'ai'
Run Code Online (Sandbox Code Playgroud)
正如Pau Guillamon所建议的,这里有一段与上面代码相当的片段:
const int i = 0;
const int& ai = i;
ai = 5;
Run Code Online (Sandbox Code Playgroud)
关于说明auto符的更多细节可以在cppreference上找到.
| 归档时间: |
|
| 查看次数: |
239 次 |
| 最近记录: |