C++ volatile multable

**类型修饰符,用它声明的变量可以被某些编译器未知的因素所修改
如:操作系统,其他进程等,遇到这个关键字声明时,编译器对访问该变量的代码不再进行优化;
可以提供特殊的稳定访问;
当要求使用 volatile 声明的变量的值的时候,系统总是重新从它所在的内存读取数据,
即使它前面的指令刚刚从该处读取过数据。而且读取的数据立刻被保存

volatile 的意思是让编译器每次操作该变量时一定要从内存中真正取出,而不是使用已经存在寄存器中的值,**

代码示例

#include <iostream>

using namespace std;

class A{
    int a;
    public:
    int f(){
        a++;
        return a;
    }
    int  f()volatile{
        
        a++;
        return a;
    }

    int f()const volatile{
        //a++; 表达式必须是一个可修改的左值
        return a;
    }
    A(int x){ a = x;}
};
 A x(3);
 const A y(6);
 const volatile A z(8);
 
int main()
{   
    cout << x.f() << endl;//输出结果为4 调用 f
    cout << y.f() << endl;//5  调用 f()const volatile
    cout << z.f() << endl;//6  调用 f()const volatile
    
    system("pause");
    return 0;
}
发布了52 篇原创文章 · 获赞 15 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/jzj_c_love/article/details/102526495