要理解 C# 中的 volatile 关键字,就要先知道编译器背后的一个基本优化原理。比如对于下面这段代码:
public class Example
{
public int x;
public void DoWork()
{
x = 5;
var y = x + 10;
Debug.WriteLine("x = " +x + ", y = " +y);
}
}
在 Release 模式下,编译器读取 x = 5 后紧接着读取 y = x + 10,在单线程思维模式下,编
为什么使用volatile ?
C/C++中的 volatile 关键字 和const对应,用来修饰变量,通常用于建立语言级别的memory barrier。这是BS在“The C++ Programming Language”对volatile修饰词的解释:
A volatile specifier is a hint to a compiler that an object may change its value in ways not specified by the language
1.mutable
在C++中,mutable是为了突破const的限制而设置的。被mutable修饰的变量,将永远处于可变的状态,即使在一个const函数中,甚至结构体变量或者类对象为const,其mutable成员也可以被修改。mutable在类中只能够修饰非静态数据成员。
#include
using namespace std;
class test
{
mutable int a;
int b;
public:
test(int _a,int _b) :a(_a),b(