【发布时间】:2015-06-16 14:59:52
【问题描述】:
今天看到一段代码是这样的:
int a = 0;
const decltype((a)) x = 10; // Error
const int b = 0;
decltype ((b)) y = 42; // Correct
我可以看到为什么正确的代码是正确的,但我看不出为什么错误的代码是不正确的。
我测试了一下,发现有点奇怪。
const decltype((a)) x = 10; 这应该定义一个const int& 对吧?但它不编译! error: non-const lvalue reference to type 'int' cannot bind to a temporary of type 'int'.
我将其更改为 const decltype((a)) x = a; 然后编译。
那么,x 是 const 引用吗?不,我发现它是一个非常量引用。我可以通过x修改a的值。
为什么const修饰符没有生效?
【问题讨论】:
-
const应用于引用(并被忽略),而不是引用的类型。 -
将
decltype与修饰符组合起来的工作方式与将修饰符应用于typedef-ed 类型完全相同。这不是文本替换。 -
@T.C. @ben-voigt 哦,我明白了。所以
const应用到int&的整个body 上就是const reference to int,而不是仅仅结合它就是const int&,引用const int...对吧? -
int是int&类型中更“内部”的类型,而 const 坚持作为参考的外部类型。只需在右侧添加 const 并读取结果类型:“const reference to int” -
@ixSci 谢谢,我完全理解你的意思。但是我很好奇为什么你们都在评论而不是回答?