标签:str c++ ati volatil strong http png names 编译器
看如下代码:
  1 #include <iostream>
  2 using namespace std;
  3 
  4 const double a = 10.5;
  5 
  6 int main() {
  7     double* p = const_cast<double*>(&a);
  8     *p = 110.5;
  9     return 0;
 10 }
编译可过,运行时,段错误。

原因是全局的const变量分配到了只读内存区。可以写如下代码验证一下:
  1 #include <iostream>
  2 using namespace std;
  3 
  4 const int a = 10.5;
  5 const int b = 10.5;
  6 
  7 int c = 100;
  8 int d = 100;
  9 
 10 int main() {
 11     cout << &a << endl;
 12     cout << &b << endl;
 13     cout << &c << endl;
 14     cout << &d << endl;
 15     return 0;
 16 }
输出内容如下所示。内存地址差了很多的。

代码如下:
  1 #include <iostream>
  2 using namespace std;
  3 
  4 int main() {
  5     const double a = 10.5;
  6     double* p = const_cast<double*>(&a);
  7     *p = 20.5;
  8     cout << a << endl;
  9     cout << *p << endl;
 10     return 0;
 11 }
编译后,输出如下图:

输出符合你的预期没? 继续执行下面代码:
 1 #include <iostream>
  2 using namespace std;
  3 
  4 int main() {
  5     volatile const double a = 10.5;
  6     double* p = const_cast<double*>(&a);
  7     *p = 20.5;
  8     cout << a << endl;
  9     cout << *p << endl;
 10     return 0;
 11 }
编译后,输出为如下图:

原因:编译器对const变量进行了优化,读取它的值时,直接从寄存器里拿。当加上volatile修饰后,编译器指示每次从内存中读取。
const 小知识点(二): 修改const修饰的变量会怎样?
标签:str c++ ati volatil strong http png names 编译器
原文地址:https://www.cnblogs.com/yinheyi/p/14630124.html