This question already has answers here:
Two different values at the same memory address
                                
                                    (7个答案)
                                
                        
                                2年前关闭。
            
                    
考虑一下:

#include <iostream>
using namespace std;

int main(void)
{
    const int a1 = 40;
    const int* b1 = &a1;
    char* c1 = (char *)(b1);
    *c1 = 'A';
    int *t = (int*)c1;


    cout << a1 << " " << *t << endl;
    cout << &a1 << " " << t << endl;

    return 0;
}


输出为:

40 65
0xbfacbe8c 0xbfacbe8c


对我来说,这几乎是不可能的,除非编译器进行了优化。怎么样 ?

最佳答案

这是undefined behavior,您正在修改const变量,因此对结果不会有任何期望。我们可以通过转到C ++标准草案的7.1.6.1 cv-qualifiers第4段看到这一点:


  在生命周期(3.8)期间修改const对象的任何尝试都会导致未定义的行为。


甚至提供了一个例子:

const int* ciq = new const int (3); // initialized as required
int* iq = const_cast<int*>(ciq); // cast required
*iq = 4; // undefined: modifies a const object


1.3.24部分中未定义行为的标准定义中,给出了以下可能的行为:


  [...]允许的不确定行为包括从完全忽略具有无法预测结果的情况到在翻译或程序执行过程中以环境特征的书面方式记录的行为(有无发行)。
  诊断消息),以终止翻译或执行(伴随诊断消息的发布)。 [...]

10-08 08:32
查看更多