C++ const 若干问题

来源:百度知道 编辑:UC知道 时间:2024/06/10 00:07:55
#include<iostream>
#include<stdio.h>

using std::cout;
using std::endl;
void changeValue( const int *a );

int main()
{
//测试一
const int test = 9;
changeValue( &test );
cout<<test<<endl;
//test 没有改变还是9

//测试二
int test31 = 10;
const int test3 = test31;
changeValue( &test3 );
cout<<test3<<endl;
//test1 没有改变还是9改变为0

//测试三
int test1 = 10;
changeValue( &test1 );
cout<<test1<<endl;
//test1 没有改变还是9改变为0

//测试四
int s = 30;
const int tag = s;
const int *cp = &tag;
*(int*)cp = 10;
cout<<tag<<endl;
//tag中的值被修改了

//测试五
const int tag1 = 30;
const int *cp1 = &tag1;
*(int*)cp1 = 10;
cout<<tag1<<endl;
//ta

我的猜测:

你把一个变量声明成const类型,就意味着你不会更改它的值,编译器能保证其不被直接修改,可能就放松了对它的控制。比如第一次访问时读到寄存器里,下次在访问时如果还在寄存器中,就不会再从内存中读取。const类型的变量不是在只读内存里的,他也是栈或者堆或者全局的可读写内存里的,如果中间你通过间接的手段改动了内存中的值(程序可读写内存里面的东西,一般没有保护,可以通过指针随便改的),编译器可能觉察不到,仍是用寄存器中的值,就会产生一些微妙的现象。

证实:

通过调试都可以看出来,const类型变量内存中值是改了的。

通过程序也可以看出,通过取地址然后复引用,输出的结果就是更改之后的:
#include<iostream>

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;
}

通过汇编可以看出,编译器直接把常变量的值替换成了常量,而没有读到寄存器或者从内存中读取,