C++ Const_Cast是否会引发新变量?

use*_*802 1 c++ const-cast

#include <iostream>

using namespace std;

int main() {
        const int a = 2;
        const int *p = &a;
        int *p2 = const_cast<int*>(p);
        *p2=5;
        char *p3 = (char *)&a;
        cout << "p2 is" << *p2 << endl;
        cout << "p2 address " << p2 << endl;
        cout << "a is " << a << endl;
        cout << "a address " << &a << endl;

        return 0;
}
Run Code Online (Sandbox Code Playgroud)

大家好!

根据输出,*p2和a具有不同的值,*p2是5,a是2.

但是,p2和&a是相同的.我糊涂了...

你能帮我理解一下这种情况吗?

非常感谢你!

Luc*_*ore 6

未定义的行为意味着任何事情都可能发生.包括这个.

5.2.11 Const cast [expr.const.cast]

7)[注意:根据目的,通过指针,左值或指针数据成员从一个产生的写操作的类型const_cast即擅自抛弃一个const限定符73可能会产生不确定的行为(7.1.6.1). - 尾注]

其根本原因可能是编译器,看怎么aconst,优化cout << "a is " << a << endl;到一个简单的cout << "a is " << 2 << endl;.

例如,即使在调试版本中,我也会得到:

        cout << "a is " << a << endl;
00CE1581  mov         esi,esp  
00CE1583  mov         eax,dword ptr [__imp_std::endl (0CFD30Ch)]  
00CE1588  push        eax  
00CE1589  mov         edi,esp  
//...
00CE158B  push        2 
//...
00CE158D  push        offset string "a is " (0CE7840h)  
00CE1592  mov         ecx,dword ptr [__imp_std::cout (0CFD308h)]  
00CE1598  push        ecx  
00CE1599  call        std::operator<<<std::char_traits<char> > (0CE1159h)  
00CE159E  add         esp,8  
00CE15A1  mov         ecx,eax  
00CE15A3  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (0CFD304h)]  
00CE15A9  cmp         edi,esp  
00CE15AB  call        @ILT+415(__RTC_CheckEsp) (0CE11A4h)  
00CE15B0  mov         ecx,eax  
00CE15B2  call        dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (0CFD300h)]  
00CE15B8  cmp         esi,esp  
00CE15BA  call        @ILT+415(__RTC_CheckEsp) (0CE11A4h)  
Run Code Online (Sandbox Code Playgroud)

我突出了重要的部分 - 2直接在参数堆栈上推送operator<<,而不是a被读取的值.