#include
#include
using std::cout;
using std::endl;
void changeValue( const int *a );
int main()
{
//test 1
const int test = 9;
changeValue( &test );
cout<<
//test 2
int test31 = 10;
const int test3 = test31;
changeValue( &test3 );
cout<<
//test 3
int test1 = 10;
changeValue( &test1 );
cout<<
//test4
int s = 30;
const int tag = s;
const int *cp = &tag;
*(int*)cp = 10;
cout<<<","<<*cp<
//test 5
const int tag1 = 30;
const int *cp1 = &tag1;
*(int*)cp1 = 10;
cout<<<","<<*cp1<
return 0;
}
void changeValue( const int *a )
{
*(int*)a = 0;
}
output:
9
0
0
10,10
30,10
下面是解释:
你把一个变量声明成const类型,就意味着你不会更改它的值,编译器能保证其不被直接修改,可能就放松了对它的控制。比如第一次访问时读到寄存器里,下次在访问时如果还在寄存器中,就不会再从内存中读取。const类型的变量不是在只读内存里的,他也是栈或者堆或者全局的可读写内存里的,如果中间你通过间接的手段改动了内存中的值(程序可读写内存里面的东西,一般没有保护,可以通过指针随便改的),编译器可能觉察不到,仍是用寄存器中的值,就会产生一些微妙的现象。
证实:
通过调试都可以看出来,const类型变量内存中值是改了的。
通过程序也可以看出,通过取地址然后复引用,输出的结果就是更改之后的:
#include
using namespace std;
int main()
{
{
const int i = 0;
*(int*)&i = 1;
cout << i << "/t" << *(int*)&i << endl;
}
{
const int i = 0;
const int j = i;
*(int*)&j = 1;
cout << j << "/t" << *(int*)&j << endl;
}
{
const int i = 0;
const int* j = &i;
*(int*)j = 1;
cout << i << "/t" << *j << endl;
}
return 0;
}
通过汇编可以看出,编译器直接把常变量的值替换成了常量,而没有读到寄存器或者从内存中读取,而普通变量,是从内存中读取的:
8: const int i = 0x12345678;
004017A8 mov dword ptr [i],12345678h
9: int j = i;
004017AF mov dword ptr [j],12345678h
10: int k = i + j;
004017B6 mov eax,dword ptr [j] //here
004017B9 add eax,12345678h //here
004017BE mov dword ptr [k],eax
本文通过几个测试案例探讨了C++中const变量的行为特性,特别是当尝试通过指针改变其值时的情况。揭示了编译器对const变量的优化方式及其潜在的影响。

被折叠的 条评论
为什么被折叠?



