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 optimizing away code.
There were some examples, such as when polling memory-mapped hardware: without volatile
the polling loop would be removed as the compiler might recognize that the condition value is never changed. But since there only were one example or maybe two, it got me thinking: Are there other situations where we need to use volatile
in terms of avoiding unwanted optimization? Are condition variables the only place where volatile
is needed?
I imagine that optimization is compiler-specific and therefore is not specified in the C++ specification. Does that mean we have to go by gut feeling, saying Hm, I suspect my compiler will do away with this if I don't declare that variable as volatile
or are there any clear rules to go by?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…