c++中const变量真的不可以修改吗?

来源:互联网 发布:手机传感器数据采集 编辑:程序博客网 时间:2024/06/01 08:03
 

c++中const变量真的不可以修改吗?


 编译器通常不为普通const常量分配存储空间,而是将它们保存在符号表中,这使得它成为一个编译期间的常量,没有了存储与读内存的操作,使得它的效率也很高。


在学c++的时候,看到的大部分的书籍对const关键字的介绍都是:const关键字修饰的变量的值是不可被修改的。但是事实真是如此吗?今天做了一个小的实验,发现const变量是可以被修改的。c++代码如下: 

[cpp] view plain copy
  1. 1 #include <iostream>  
  2.  2 using namespace std;  
  3.  3   
  4.  4 int main()  
  5.  5 {  
  6.  6     const int a = 3;  
  7.  7     int* p = const_cast<int*>(&a);  
  8.  8     *p = 4;  
  9.  9     cout << "value of p: " << *p << endl;  
  10. 10     cout << "value of a: " << a << endl;  
  11. 11     cout << "address of p: " << p << endl;  
  12. 12     cout << "address of a: " << &a << endl;  
  13. 13   
  14. 14     return 0;  
  15. 15 }               

上面代码第7行将a的地址赋值给指针p,然后第8行修改p所指向的地址中的值,运行结果如下:
运行结果
value of p: 4
value of a: 3
address of p: 0x7fbffff7fc
address of a: 0x7fbffff7fc



原因:  const int a其实是保存在符号表中,无内存地址,但自己对a进行&a,那么编译器会为a分配一个地址,但取a的值依然是从符号表中取值,而用指针int *p=&a;

*p=4这个值是改变a的内存所表示值,不会改变符号表中a的值




[cpp] view plain copy
  1. 1 #include <iostream>  
  2.  2 using namespace std;  
  3.  3 const int a = 3;  
  4.  4 int main()  
  5.  5 {  
  6.  6     //const int a = 3;  
  7.  7     int* p = const_cast<int*>(&a);  
  8.  8     *p = 4;  
  9.  9     cout << "value of p: " << *p << endl;  
  10. 10     cout << "value of a: " << a << endl;  
  11. 11     cout << "address of p: " << p << endl;  
  12. 12     cout << "address of a: " << &a << endl;  
  13. 13   
  14. 14     return 0;  
  15. 15 }  

如上代码g++编译通过,在运行时报错如下:
输出结果
Segmentation fault (core dumped)
由此可见,在c++中全局const变量和局部const变量的编译器处理的方法是不一样的。查阅资料得知,全局const变量是不分配内存地址的,它编译器放置在符号表中作为编译期常量,全局const变量放在只读数据段中,受到只读数据段的权限保护,当你修改一个只读数据段中的内容时,会得到一个运行时错误。而局部const变量是放在堆栈之中,因为在内存中有地址,通过修改地址中的值可以达到修改const所指内存中值的目的。


原创粉丝点击