What kinds of optimizations does 'volatile' prevent in C++?

后端 未结 8 1887
Happy的楠姐
Happy的楠姐 2020-11-27 17:04

I was looking up the keyword volatile and what it\'s for, and the answer I got was pretty much:

It\'s used to prevent the compiler from o

8条回答
  •  误落风尘
    2020-11-27 17:29

    Basically, volatile announces that a value might change behind your program's back. That prevents compilers from caching the value (in a CPU register) and from optimizing away accesses to that value when they seem unnecessary from the POV of your program.

    What should trigger usage of volatile is when a value changes despite the fact that your program hasn't written to it, and when no other memory barriers (like mutexes as used for multi-threaded programs) are present.

提交回复
热议问题