加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 引用和它指向的变量有不同的值吗?

发布时间:2020-12-16 10:36:41 所属栏目:百科 来源:网络整理
导读:参见英文答案 Weird Behaviour with const_cast ????????????????????????????????????2个 我无法理解为什么在下面的代码片段引用及其相关变量给出不同的结果. const int x = 10;const int ptr = x; int y = const_castint(ptr);y = 19;std::cout "x = " x "
参见英文答案 > Weird Behaviour with const_cast ????????????????????????????????????2个
我无法理解为什么在下面的代码片段引用及其相关变量给出不同的结果.

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有关吗?

解决方法

从5.2.11 Const cast [expr.const.cast]:

Note: Depending on the type of the object,a write operation through the pointer,lvalue or pointer
to data member resulting from a const_cast that casts away a const-qualifier may produce undefined
behavior (7.1.6.1). — end note ]

你正在执行未定义的行为,所以你很幸运,你的计算机没有内爆.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读