c++中const变量真的不可以修改吗?
3252 点击·0 回帖
![]() | ![]() | |
![]() | 在学c++的时候,看到的大部分的书籍对const关键字的介绍都是:const关键字修饰的变量的值是不可被修改的。但是事实真是如此吗?今天做了一个小的实验,发现const变量是可以被修改的。c++代码如下: 1 #include <iostream> 2 using namespace std; 3 4 int main() 5 { 6 const int a = 3; 7 int* p = const_cast<int*>(;a); 8 *p = 4; 9 cout << "value of p: " << *p << endl; 10 cout << "value of a: " << a << endl; 11 cout << "address of p: " << p << endl; 12 cout << "address of a: " << ;a << endl; 13 14 return 0; 15 } 上面代码第7行将a的地址赋值给指针p,然后第8行修改p所指向的地址中的值,运行结果如下: 运行结果 value of p: 4 value of a: 3 address of p: 0x7fbffff7fc address of a: 0x7fbffff7fc 如上所示结果,指针p所指向的地址和变量a的地址相同,但是p所指地址中的值已经发生改变。但是为何变量a对应的地址中的值已经由3变为4,但是a的值确实3呢? 暂时把这个问题搁浅。再来看一下如下的c++代码: 1 #include <iostream> 2 using namespace std; 3 const int a = 3; 4 int main() 5 { 6 //const int a = 3; 7 int* p = const_cast<int*>(;a); 8 *p = 4; 9 cout << "value of p: " << *p << endl; 10 cout << "value of a: " << a << endl; 11 cout << "address of p: " << p << endl; 12 cout << "address of a: " << ;a << endl; 13 14 return 0; 15 } 如上代码g++编译通过,在运行时报错如下: 输出结果 Segmentation fault (core dumped) 由此可见,在c++中全局const变量和局部const变量的编译器处理的方法是不一样的。查阅资料得知,全局const变量是不分配内存地址的,它编译器放置在符号表中作为编译期常量,全局const变量放在只读数据段中,受到只读数据段的权限保护,当你修改一个只读数据段中的内容时,会得到一个运行时错误。而局部const变量是放在堆栈之中,因为在内存中有地址,通过修改地址中的值可以达到修改const所指内存中值的目的。 | |
![]() | ![]() |