A lot of people are saying "volatile member function is completely analogous to how const works."
They are quite similar in the sense of if a pointer is marked as const/volatile, it can only access member functions marked as const/volatile.
But actually defining a member function as const has an additional effect, which makes the function read-only. Any modifications of the object inside the function will cause a compiler error. Is there such analogs in volatile member function?
Well, a volatile member function will make the object members volatile, that is, this
will be as if it were defined volatile T * const this
. And as a consequence, any reference to a member variable is also volatile.
Remember that volatile read/writes are operations that cannot be elided/reordered by the compiler. They are usually used to implement memory-mapped hardware devices or things like that.
Frankly speaking I've never been a use of this feature, other than doing smart tricks to filter the access to the function, not to make use of the volatile-ness of the object. If your code is low level enough to need volatile
you probably will want to go putting the volatile just in the variables you need.
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