
我无法理解为什么在下面的代码片段引用及其相关变量给出不同的结果.
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 aconst_castthat casts away a const-qualifIEr may produce undefined
behavior (7.1.6.1). — end note ]
你正在执行未定义的行为,所以你很幸运,你的计算机没有内爆. 总结
以上是内存溢出为你收集整理的c – 引用和它指向的变量有不同的值吗?全部内容,希望文章能够帮你解决c – 引用和它指向的变量有不同的值吗?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)