个人学习记录,仅作参考。
// Example program
#include <iostream>
#include <string>
int main()
{
int const volatile a = 10; //volatile key word
std::cout << "===[a = 10]===" << std::endl;
std::cout << " a : " << a << std::endl;
std::cout << "&a : " << (int *)&a << std::endl;
int *p = const_cast<int *>(&a);
*p = 20;
std::cout << "===[*p = 20]==="<< std::endl;
std::cout << " a : " << a << std::endl; // a can be modified by pointer p if use volatile
std::cout << "&a : " << (int *)&a << std::endl;
std::cout << "*p : " << *p << std::endl;
std::cout << " p : " << p << std::endl;
int &r = const_cast<int &>(a);
r = 30;
std::cout << "===[r = 30]==="<< std::endl;
std::cout << " a : " << a << std::endl; // a can be modified by reference r if use volatile
std::cout << "&a : " << (int *)&a << std::endl;
std::cout << "*p : " << *p << std::endl;
std::cout << " p : " << p << std::endl;
std::cout << " r : " << r << std::endl;
std::cout << "&r : " << (int *)&r << std::endl;
}
C++在线编译测试
C++中:
1.如果不用volatile关键字修饰const常量,即int const a = 10;
,后续访问取自寄存器(默认优化导致)。
- 输出:
===[a = 10]===
a : 10
&a : 0x7d37b0eabdbc
===[*p = 20]===
a : 10
&a : 0x7d37b0eabdbc
*p : 20
p : 0x7d37b0eabdbc
===[r = 30]===
a : 10
&a : 0x7d37b0eabdbc
*p : 30
p : 0x7d37b0eabdbc
r : 30
&r : 0x7d37b0eabdbc
2.如果使用volatile关键字修饰const常量,即int const volatile a = 10;
,后续访问取自内存。
- 输出:
===[a = 10]===
a : 10
&a : 0x7493aadc141c
===[*p = 20]===
a : 20
&a : 0x7493aadc141c
*p : 20
p : 0x7493aadc141c
===[r = 30]===
a : 30
&a : 0x7493aadc141c
*p : 30
p : 0x7493aadc141c
r : 30
&r : 0x7493aadc141c