【发布时间】:2016-05-05 12:58:45
【问题描述】:
我不明白为什么在下面的代码中 sn-p 引用及其相关变量给出了不同的结果。
const int x = 10;
const int &ptr = x;
int& y = const_cast<int&>(ptr);
y = 19;
std::cout << "x = " << x << " ptr=" << ptr << " y=" << y << std::endl;
输出:
x=10 ptr=19 y=19
根据我的理解,引用只是变量的别名,那么为什么 ptr 是 19 而x 是 10?这与const 或const_cast 有关吗?
【问题讨论】:
-
这是未定义的行为。你的冰箱可能会爆炸,就像你得到这个结果一样。
-
修改常量值时,行为未定义。
标签: c++ casting reference constants