简体   繁体   中英

volatile member function vs. constant member function in C++

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.

Short answer: yes.

If an instance of an object is declared volatile then it is an error to call non-volatile methods on it (or for those methods to call other non-volatile methods).

A non-volatile instance can still call volatile methods, but not that it is perfectly legal to have two otherwise identical methods in a class - one volatile and one not. In that case a non-volatile instance will call the non-volatile version of the method.

But actually defining a member function as const has an additional effect, which makes the function read-only.

That's a bit of a misconception. It doesn't make the member function read-only - it makes *this const . There's a small, but important, difference between the two (the member function can still modify mutable members, and if it wants to be nasty, it can cast away the const -ness of *this to modify anything it wants, and the compiler won't complain).

And a volatile member function works in the exact same way - it makes *this volatile .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM