这里是代码示例。
a. int ii = 0;
b. const int ci = ii;
c. auto e = &ci; --> e is const int *
d. auto &f = 42; --> invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’
e. const auto &g = 42 --> ok
观察:
1. 对于 c) 子句,自动推导类型 const
2. 对于子句d),不会自动推导出类型const
3. 对于条款 e),必须手动添加类型 const 才能使其工作。
为什么子句 c 而不是 d 会自动推导类型 const?
最佳答案
原因不是 const-ness,而是 r-value-ness。
您不能对右值进行非常量引用。
如果您想知道什么是 r 值,最初的想法是只能位于赋值右侧的东西。
为了获取编译时常量的地址,编译器首先复制它,并为您提供该地址。要启用该行为,引用必须明确为 const
。
要完成答案: 案例
- c)
ci
的类型是const int
,因此&ci
的类型是const int
的地址>. - d)
42
的类型是int
。auto
推导为int
,f
被声明为对int
的引用,但未能绑定(bind)到 r-value - e)
g
的类型是const int &
,可以绑定(bind)编译时间常量。
关于C++ : Different deduction of type auto between const int * and cont int &,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32873834/