扫除一切菜鸟 扫除一切菜鸟
关注数: 0 粉丝数: 46 发帖数: 6,298 关注贴吧数: 2
关于C/C++中的const 在C++吧看到这样的问题, 以前没引起多大注意, 但细看之下, 猫腻不少.....首先看看如下C++代码(所有测试在VC6.0下进行):#include int main(){    const int i = 1;    int b;    *(int*)&i = 4;    b = 4 + 1;    std::cout << "i = " << i << std::endl;    return 0; }依常理看运行结果应该是4,但它确是1!有几种直接看似合理的解释:1. *(int*)&i = 4;没有被执行,或者编译器做了手脚,阻止了i的修改;2. i被移入寄存器,cout入栈参数i被某个寄存器代替,比如push ebx;3. 所有使用i的地方,i的值被立即数代替,cout压入的实则为1,push 1;为了证明某个解释的正确,我们最好看看反汇编代码:3:    int main(){00401570   push        ebp00401571   mov         ebp,esp00401573   sub         esp,48h00401576   push        ebx00401577   push        esi00401578   push        edi00401579   lea         edi,[ebp-48h]0040157C   mov         ecx,12h00401581   mov         eax,0CCCCCCCCh00401586   rep stos    dword ptr [edi]4:5:        const int i = 1;00401588   mov         dword ptr [ebp-4],16:        int b;7:        *(int*)&i = 4;0040158F   mov         dword ptr [ebp-4],48:9:        b = 4 + 1;00401596   mov         dword ptr [ebp-8],510:       std::cout << "i = " << i << std::endl;0040159D   push        offset @ILT+195(std::endl) (004010c8)004015A2   push        1004015A4   push        offset string "i = " (0046c01c)004015A9   push        offset std::cout (004777e0)004015AE   call        @ILT+640(std::operator<<) (00401285)
首页 1 2 下一页