There has been a lot of debate going on concerning the usefulness of volatile
in multi-threaded code. Most people agree, that the principal usecases of volatile
are mostly for bare metal applications such as device drivers and interrupt handlers, but not to make a variable of built-in type thread-safe. In fact, volatile has lead to much confusion because of this.
However, it has been added to function overloads of std::atomic<T>
types, which suggests that there be a usecase for this. What are usecases of these operations?
There is a general usefulness to volatile
in the sense that compiler MUST not optimise away accesses to that variable. However, in this case, I think it's mainly because the input MAY be volatile
- just like in case of const
, you can "add" but not "remove" volatile
attribute to a passed in paramater.
Thus:
int foo(volatile int *a)
{
...
}
will accept:
int x;
volatile int y;
foo(&x);
foo(&y);
where if you didn't write volatile
, the compiler should not accept the foo(&y);
variant.