Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is volatile deprecated in C++20?

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?

like image 530
康桓瑋 Avatar asked Dec 07 '19 07:12

康桓瑋


People also ask

Why is volatile deprecated in C++?

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.

Is volatile keyword deprecated?

One interesting of these minor improvements is that most of volatile has been deprecated.

Is volatile deprecated in C++?

The new C++ standard, C++20, has deprecated volatile !

Why is volatile needed in C?

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.


1 Answers

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.


Motivating (Ambiguous) Examples

  • Volatile bit Fields should be specified by your hardware manual and/or compiler.
  • Is += a single/atomic instruction? How about ++?
  • How many reads/writes are needed for compare_exchange? What if it fails?
  • What does void foo(int volatile n) mean? or int volatile foo()?
  • Should *vp; do a load? (This has changed twice in the standard.)

Threading

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.

like image 195
unDeadHerbs Avatar answered Oct 19 '22 04:10

unDeadHerbs