您的位置:首页 > 移动开发 > IOS开发

关于 const_cast的有意思的问题

2009-05-08 17:51 316 查看
 #include   <iostream>  
   
  using   namespace   std;  
   
  int   main()  
 {  
          //TODO:   Add   your   code   here  
          const   int   a   =   1;  
          int   *p   =   0;  
          cout   <<   "a   =   "   <<   a   <<   endl;  
           
          //!:   p   =   &a   can   not   cast   a   const   int*   to   int*  
          p   =   const_cast<int*>(&a);  
           
          *p   =   5;  
          cout   <<   "a   =   "   <<   a   <<   endl;  
          cout   <<   "*p   =   "   <<   *p   <<   endl;  
           
          int   b;cin   >>   b     ;  
          return   0;  
  }  
   
  请问程序的结果为什么是  
  a   =   1  
  a   =   1  
  *p   =   5  
  而不是  
  a   =   1  
  a   =   5  
  *p   =   5   
    
答案:
对于常量,是编译时直接求值的(无需求值的直接替换).
          cout   <<   "a   =   "   <<   a   <<   endl;  
相当于
          cout   <<   "a   =   "   <<   1   <<   endl;  

其实a所在的内存的值已经改为5了.

通过汇编代码可以看清楚:
  16:               cout   <<   "a   =   "   <<   a   <<   endl;  
  004015E4       push                 offset   @ILT+195(std::endl)   (004010c8)    // 参数''a=''入栈
  004015E9       push                 1                                                                    // 参数a入栈
  17:               cout   <<   "*p   =   "   <<   *p   <<   endl;  
  0040160B       push                 offset   @ILT+195(std::endl)   (004010c8)  
  00401610       mov                   edx,dword   ptr   [ebp-8]  
  00401613       mov                   eax,dword   ptr   [edx]                                    // 参数*p入栈
  对P的操作和一般的指针变量完全一样,先找地址,然后取值。  
  对a的操作根本就直接用1,所以cout<<a看起来就象cout<<"1";
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  iostream include 汇编 c