According to cppreference, most uses of the volatile
keyword are to be deprecated in C++20. What is the disadvantage of volatile
? And what is the alternative solution when not using volatile
?
The C++ library now (since C++11) provides a correct means of ensuring atomic access of variables, so it makes sense to discourage programmers from incorrectly using volatile when the intent is atomic access.
One interesting of these minor improvements is that most of volatile has been deprecated.
The new C++ standard, C++20, has deprecated volatile !
The volatile keyword is intended to prevent the compiler from applying any optimizations on objects that can change in ways that cannot be determined by the compiler. Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time.
There's a good talk by the C++ committee language evolution chair on why.
Brief summary, the places that volatile
is being removed from didn't have any well defined meaning in the standard and just caused confusion.
+=
a single/atomic instruction? How about ++
?compare_exchange
? What if it fails?void foo(int volatile n)
mean? or int volatile foo()
?*vp;
do a load? (This has changed twice in the standard.)Historically, people have used volatile
to achieve thread safety in C and C++. In C++11, non-UB ways to create synchronization and shared state between threads were added. I recommend Back to Basics: Concurrency as a good introduction.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With