C++ const 引用允许从表达式进行更改吗?

xyz*_*xyz 3 c++

在《C++ Primer 5th Edition》中有关 const 引用的部分中,有一个小示例块:

int i = 42;
const int &r1 = i; // we can bind a const int& to a plain int object
const int &r2 = 42; // ok: r1 is a reference to const
const int &r3 = r1 * 2; // ok: r3 is a reference to const
int &r4 = r * 2; // error: r4 is a plain, non const reference
Run Code Online (Sandbox Code Playgroud)

在第四行,我只是好奇常量引用的常量引用如何能够成功地将值乘以 2。当 r1 引用 i 时,不会发生转换,使所有内容都成为常量吗?或者第 4 行中的表达式对于 r3 来说是独立的吗?

Bri*_*ian 5

在这一行

const int& r3 = r1 * 2;
Run Code Online (Sandbox Code Playgroud)

创建临时变量int并从初始化表达式复制初始化r1 * 2,然后r3绑定到临时变量。这不会r1比评估修改更多地3 * 2修改指称3

  • 请注意,临时左值与引用具有相同的生命周期 (2认同)