Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 510
Alex Avatar asked Oct 20 '22 19:10

Alex


1 Answers

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.

like image 187
rodrigo Avatar answered Oct 27 '22 09:10

rodrigo