【发布时间】:2019-02-21 16:03:53
【问题描述】:
在 C++ 中,const & 的值可以改变吗?
嗯,当然不能改变,不是吗?这就是const 的意思。此外,请听 Stroustrup:
const左值引用指的是一个常量,从引用用户的角度来看,它是不可变的。
但是这个呢?
#include <iostream>
int main() {
int a = 0;
const int& r = a;
const int old_r = r;
++a;
const int new_r = r;
std::cout
<< "old_r == " << old_r
<< " but new_r == " << new_r << std::endl;
return 0;
}
在我的机器上,这个输出,old_r == 0 but new_r == 1。
这就是我真正的问题。在上面的代码中,看一行
const int new_r = r;
只要
- 地址
&new_r既没有在这一行也没有在代码的其他地方提取,并且 - 代码没有
volatile,
是否会阻止优化编译器将 old_r 和 new_r 合并为单个常量对象,将行视为如下所示?
const int& new_r = old_r;
我问是因为,据我所知,如果编译器这样做优化,那可能会改变行为。程序可能会输出old_r == 0 but new_r == 0。
相关问题
我发现的最相关的现有问题是这个:
- (C语言)Can const be changed?(特别是链接问题的第1点。)
以下也是相关的,但与当前问题不同,涉及演员表:
- Changing the value of a const
- Two different values at the same memory address
- Modifying constant object
- Changing the value of const variable [duplicate]
- (C语言)Accessing a non-const through const declaration
- (C语言)Can we modify the value of a const variable?
- (C语言)Const variable value is changed by using a pointer
- (C语言)Confusion regarding modification of const variable using pointers
- (C语言)Weird Behaviour with const_cast [duplicate]
另见N4659(C++17 标准草案),第 2 节。 10.1.7.1,“cv 限定符。”
问题顶部的 Stroustrup 引用来自 sect. C++ 编程语言, 第 4 版的 7.7.2。当然,没有一个作者可以把一千页的书里的每一句话都写得完美无缺。然而,也许 Stroustrup 是清楚的,而我只是把他读错了。不过,您可能会明白为什么这句话让我感到困惑。这就是我问的原因。
【问题讨论】:
-
当然可以,这也是
const T&参数使函数比按值传递相同参数更难优化的原因之一。
标签: c++ reference constants undefined-behavior const-reference