What does it mean when member function is volatile?

I usually see the const specifier used to specify the const member function. But what does this mean when the volatile keyword is used?

 void f() volatile {} 

This compiles for me, but I don’t understand what it is for. I could not find any information about this in my search, so any help would be appreciated.

Update. To be clear, I know what volatile . I just don't know what this means in this context.

+10
c ++
May 25 '13 at 3:22
source share
3 answers

The volatile qualifier for a member function is similar to the const classifier. It allows you to call a member function on volatile objects:

 struct A { void f() volatile {} void g() {} }; int main() { A volatile a; af(); // Allowed ag(); // Doesn't compile } 
+14
May 25 '13 at 3:28
source share

In a member function, const and volatile qualifiers refer to *this . Access to any instance members inside this member function will then be volatile access, with the same semantics as any volatile variable. In particular, non- volatile member functions cannot be called by the volatile object, and volatile is applied to overload in the same way as const :

 #include <iostream> class C { public: void f() { std::cout << "f()\n"; } void f() const { std::cout << "f() const\n"; } void f() volatile { std::cout << "f() volatile\n"; } void f() const volatile { std::cout << "f() const volatile\n"; } }; int main() { C c1; c1.f(); const C c2; c2.f(); volatile C c3; c3.f(); const volatile C c4; c4.f(); } 
+9
May 25 '13 at 3:28
source share

Objects declared as mutable are not used for certain optimizations, since their values ​​can change at any time. The system always reads the current value of the volatile object at the requested point, even if the previous command requested the value from the same object. In addition, the value of the object is recorded immediately upon assignment.

A volatile object can only call unstable member functions.

Thus, by marking a member function as mutable, you will make any access to non-static data elements of the object inside this member function as mutable.

+2
May 25 '13 at 3:38
source share



All Articles