[英]'const decltype((a))' does not declare a const reference?
Today I saw some code like this: 今天我看到了一些这样的代码:
int a = 0;
const decltype((a)) x = 10; // Error
const int b = 0;
decltype ((b)) y = 42; // Correct
I can see why the correct code is correct, but I can't see why the incorrect code is incorrect. 我可以看到为什么正确的代码是正确的,但我不明白为什么错误的代码不正确。
I tested it, and just found it a little wierd. 我测试了它,发现它有点奇怪。
const decltype((a)) x = 10;
This should be defining a const int&
right? 这应该定义一个const int&
right? But it doesn't compile! 但它不编译! error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
. error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'
。
I changed it to const decltype((a)) x = a;
我将它改为const decltype((a)) x = a;
then it compiles. 然后它编译。
Well, is x
a const reference? 那么, x
是一个const参考吗? No, I found that it's a non-const reference. 不,我发现它是一个非const引用。 I can modify a
's value through x
. 我可以通过x
修改a
值。
Why didn't the const
modifier take effect? 为什么const
修饰符不起作用?
Incorrect part is incorrect because const
is applied to the full type which is int&
and adding const
to int&
makes it int& const
which is const reference to int . 不正确的部分是不正确的,因为const
应用于完整类型,即int&
并将const
添加到int&
使其成为int& const
,这是const对int的引用 。 But the reference is const
by its very nature so the const part is just ignored. 但是引用本质上是const
,所以const部分只是被忽略了。 Hence the resulting type is still int&
因此,结果类型仍然是int&
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.