同一地址的变量如何产生2个不同的值?

shr*_*dur 6 c++ casting const undefined-behavior

考虑一下:

#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;
}
Run Code Online (Sandbox Code Playgroud)

这个输出是:

40 65 
0xbfacbe8c 0xbfacbe8c
Run Code Online (Sandbox Code Playgroud)

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

Sha*_*our 14

这是未定义的行为,您正在修改const变量,因此您不能期望结果.我们可以通过参考草案C++标准部分7.1.6.1 cv-qualifiers4段来看到这一点:

[...]任何在其生命周期内修改const对象的尝试(3.8)都会导致未定义的行为.

甚至提供了一个例子:

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
Run Code Online (Sandbox Code Playgroud)

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

[...]允许的未定义行为包括完全忽略不完全结果的情况,在翻译或程序执行期间以环境特征(有或没有发出诊断消息)的文件化方式行事,终止翻译或执行(发出诊断消息).[...]