本文介绍了const_cast的奇怪行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

我声明一个新的引用端,通过const_cast将其赋值给a。然后,我只需增加参考值即可打印地址和值。

I declare a new reference end assign it to value a via const_cast. Then I just increase the reference value print the addresses and values.

#include <iostream>
using namespace std;
int main()
{
    const int a = 7;
    int &b = const_cast<int&>(a);
    ++b;
    cout<<"Addresses  "<<&a<<" "<<&b<<endl;
    cout<<"Values  "<<a<<" "<<b<<endl;
}

//output
Addresses  0x7fff11f8e30c 0x7fff11f8e30c
Values  7 8

我如何在同一个地址中拥有2个不同的值?

How can i have 2 different values in the same address??

推荐答案

修改常量对象提供未定义的行为,因此您的程序(原则上)可以执行任何操作。

Modifying a constant object gives undefined behaviour, so your program could (in principle) do anything.

保持此行为未定义的原因之一是允许优化用其常量替换常量值(因为您已经声明了值永远不会改变)。这就是这里发生的情况: a 在编译时被替换为值 7 ,因此无论什么值都将保留该值您尝试在运行时执行此操作。

One reason for leaving this behaviour undefined is to allow the optimisation of replacing a constant variable with its value (since you've stated that the value can never change). That's what is happening here: a is replaced with the value 7 at compile time, and so will keep that value whatever you try to do to it at run time.

这篇关于const_cast的奇怪行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 02:11