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

后端 未结 8 1828
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:34

    The observable behavior of a C++ program is determined by read and writes to volatile variables, and any calls to input/output functions.

    What this entails is that all reads and writes to volatile variables must happen in the order they appear in code, and they must happen. (If a compiler broke one of those rules, it would be breaking the as-if rule.)

    That's all. It's used when you need to indicate that reading or writing a variable is to be seen as an observable effect. (Note, the "C++ and the Perils of Double-Checked Locking" article touches on this quite a bit.)


    So to answer the title question, it prevents any optimization that might re-order the evaluation of volatile variables relative to other volatile variables.

    That means a compiler that changes:

    int x = 2;
    volatile int y = 5;
    x = 5;
    y = 7;
    

    To

    int x = 5;
    volatile int y = 5;
    y = 7;
    

    Is fine, since the value of x is not part of the observable behavior (it's not volatile). What wouldn't be fine is changing the assignment from 5 to an assignment to 7, because that write of 5 is an observable effect.

提交回复
热议问题