C++ : const int * 和 cont int & 之间的 auto 类型不同的扣除
C++ : Different deduction of type auto between const int * and cont int &
以下是代码示例。
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。
不能使用非const引用指向r值
如果你想知道什么是r值,最初的想法是只能在赋值的右边。
要获取编译时常数的地址,编译器首先复制它,然后给你该地址。要启用该行为,引用必须显式地为const
。
完成答案:情况下
- c)
ci
的类型为const int
,因此&ci
的类型为const int
的地址。 - d)
42
的类型为int
。auto
被推导为int
,f
被声明为int
的引用,但是没有绑定到r值 - e)
g
的类型为const int &
,可以绑定编译时间常数。
这是因为42
的类型不是const int
,而是int
。它是一个右值,这意味着它不能绑定到左值引用(除非它是对const
的引用),但它仍然是int
类型。这就是auto
的推断。
如果你尝试用ci
代替42
,你会发现它工作:
auto &e = ci;
In
auto &f = 42;
42
的类型是int
,所以auto &f
变成了int &f
。现在42
是编译时字面量,因此它是一个r值。我们不能将r值绑定到引用,因此会出现编译错误。当你使用
const auto &g = 42
g
现在是const int &
, const &
可以绑定到一个临时对象,并延长它的生存期。
我想你对正在发生的事情有一点困惑。你的c没有试图推断关于const
的任何事情。ci
是const int
(int是const)。&ci
是const int *
(指向const int类型的非const指针)。auto不能仅仅是int *
,否则就会破坏const契约。
正如其他人所提到的,因为你试图将非const引用绑定到右值(数字'42'不一定存在于内存中的任何地方,因此你怎么能形成对它的引用…将来你可以修改吗?)。对于e,编译器现在愿意把42放在内存的某个地方,因为你刚刚承诺你不会改变它。
- 为什么 int 类型的枚举类值不能用作 int
- 如何将文本文件的特定行读取到 int 类型的数组中C++?
- int* 和 int[] 类型对二进制运算符 + 的操作数无效
- 比较两个整数在C++中与未知 int 类型的相等性
- 二进制'operator+' 'int*'和'int*'类型的无效操作数
- 使用元编程选择 int 类型,将生成错误
- 从数组创建 Mat 时,'cv::Mat' 和 'int' 类型不兼容
- 复制初始化 - 从 'int' 类型转换为非标量类型
- 初始化cv :: mat ::具有int类型的定义大小的人
- 处理代码重新定义int类型(uint16_t,int16_t等),并不喜欢它
- 为什么没有"int"类型声明时输出不同?
- 在大型程序中将长变量更改为 int 类型
- 无法将 int 类型转换为时间类型(我的类类型)
- C++:无法在按位函数后将 int 类型设置为非标量
- 无法分配给INT类型的成员[10]
- C++ cin 将字符串读取到 int 类型中返回 0
- 为什么 decltype((i)) 是引用类型,而 decltype(i+0) 是 int 类型
- 使用4用于循环的4矩阵上的数组下标的“ int [int]类型”
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- 正在施放带有“ Int”类型的临时性