C++ : const int * 和 cont int & 之间的 auto 类型不同的扣除

C++ : Different deduction of type auto between const int * and cont int &

本文关键字:int 类型 auto const C++ cont 之间      更新时间:2023-10-16

以下是代码示例。

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的类型为intauto被推导为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的任何事情。ciconst int (int是const)。&ciconst int *(指向const int类型的非const指针)。auto不能仅仅是int *,否则就会破坏const契约。

正如其他人所提到的,因为你试图将非const引用绑定到右值(数字'42'不一定存在于内存中的任何地方,因此你怎么能形成对它的引用…将来你可以修改吗?)。对于e,编译器现在愿意把42放在内存的某个地方,因为你刚刚承诺你不会改变它。