常量折叠
时间:2010-11-12 来源:liurhyme
c++里的常量折叠(或者常量替换)是将const常量放在符号表中,而并不给其分配内存。编译器直接进行替换优化。
#include <iostream>
using namespace std;
int main(void)
{
const int a=10;
int * p = (int*)&a;//为了能尝试通过*p修改常量a的值,用了强制转换
cout<<"a = "<< a<<endl; //输出 a = 10
cout<<"*p= "<<*p<<endl; //输出 *p = 10
*p=100; //试图修改a的值
cout<<"a = "<< a<<endl; //仍然输出: a = 10
cout<<"*p= "<<*p<<endl; //这里却输出: *p = 100
system("pause");
}
以下是 cout<<"a = "<< a<<endl;
这一句在DEBUG时的汇编代码:
004114DB mov esi,esp
004114DD mov eax,dword ptr [__imp_std::endl (41A344h)]
004114E2 push eax
004114E3 mov edi,esp
004114E5 push 0Ah ;;;;;;;注意这里是个10,是个立即数
004114E7 push offset string "*p=" (417704h)
004114EC mov ecx,dword ptr [__imp_std::cout (41A348h)]
004114F2 push ecx
004114F3 call std::operator<<<std::char_traits<char> > (411159h)
004114F8 add esp,8
004114FB mov ecx,eax
004114FD call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (41A34Ch)]
00411503 cmp edi,esp
00411505 call @ILT+410(__RTC_CheckEsp) (41119Fh)
0041150A mov ecx,eax
0041150C call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (41A32Ch)]
00411512 cmp esi,esp
00411514 call @ILT+410(__RTC_CheckEsp) (41119Fh)
#include <iostream>
using namespace std;
int main(void)
{
const int a=10;
int * p = (int*)&a;//为了能尝试通过*p修改常量a的值,用了强制转换
cout<<"a = "<< a<<endl; //输出 a = 10
cout<<"*p= "<<*p<<endl; //输出 *p = 10
*p=100; //试图修改a的值
cout<<"a = "<< a<<endl; //仍然输出: a = 10
cout<<"*p= "<<*p<<endl; //这里却输出: *p = 100
system("pause");
}
以下是 cout<<"a = "<< a<<endl;
这一句在DEBUG时的汇编代码:
004114DB mov esi,esp
004114DD mov eax,dword ptr [__imp_std::endl (41A344h)]
004114E2 push eax
004114E3 mov edi,esp
004114E5 push 0Ah ;;;;;;;注意这里是个10,是个立即数
004114E7 push offset string "*p=" (417704h)
004114EC mov ecx,dword ptr [__imp_std::cout (41A348h)]
004114F2 push ecx
004114F3 call std::operator<<<std::char_traits<char> > (411159h)
004114F8 add esp,8
004114FB mov ecx,eax
004114FD call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (41A34Ch)]
00411503 cmp edi,esp
00411505 call @ILT+410(__RTC_CheckEsp) (41119Fh)
0041150A mov ecx,eax
0041150C call dword ptr [__imp_std::basic_ostream<char,std::char_traits<char> >::operator<< (41A32Ch)]
00411512 cmp esi,esp
00411514 call @ILT+410(__RTC_CheckEsp) (41119Fh)
相关阅读 更多 +