I have a question about the difference between volatile and mutable. I noticed that both of the two means that it could be changed. What else? Are they the same thing? What's the difference? Where are they applicable? Why the two ideas are proposed? How to use them in different way?
Thanks a lot.
Mutable keyword in C++?Mutable data members are that kind of member, which can be changed always. Even if the object is const type. When we need only one member as variable and other as constant, then we can make them mutable.
1. Volatile memory is the type of memory in which data is lost as it is powered-off. Non-volatile memory is the type of memory in which data remains stored even if it is powered-off.
C's volatile keyword is a qualifier that is applied to a variable when it is declared. It tells the compiler that the value of the variable may change at any time--without any action being taken by the code the compiler finds nearby.
Here we will see what is the meaning of volatile qualifier in C++. The volatile qualifier is applied to a variable when we declare it. It is used to tell the compiler, that the value may change at any time.
A mutable
field can be changed even in an object accessed through a const
pointer or reference, or in a const
object, so the compiler knows not to stash it in R/O memory. A volatile
location is one that can be changed by code the compiler doesn't know about (e.g. some kernel-level driver), so the compiler knows not to optimize e.g. register assignment of that value under the invalid assumption that the value "cannot possibly have changed" since it was last loaded in that register. Very different kind of info being given to the compiler to stop very different kinds of invalid optimizations.
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