Call volatile member function using mutable object in C ++

What happens if you call the volatile member function with an unmodified object ?

#include <iostream> using namespace std; class A { private: int x; public: void func(int a) volatile //volatile function { x = a; cout<<x<<endl; } }; int main() { A a1; // non volatile object a1.func(10); return 0; } 
+5
source share
2 answers

The rule is the same as const member function. A volatile member function can be called on a non- volatile object, but a non- volatile member function cannot be called on a volatile object.

In your case A::func() will be fined. If you make them the opposite, compilation will fail.

 class A { private: int x; public: void func(int a) // non-volatile member function { x = a; cout<<x<<endl; } }; int main() { volatile A a1; // volatile object a1.func(10); // fail return 0; } 
+7
source

You can call it as a const function for an object that is not a constant, but for various reasons.

The volatile qualifier makes this parameter implicitly treated as a pointer to a mutable object.

Essentially, this means that the semantics of mutable objects will be applied when accessing the element (s) of the object's data. Any reading of x cannot be optimized, even if the compiler can prove that there is no last record after the last read.

Naturally, if the object is not really mutable, the func body is still correct, although not as optimized as it can be. So you can call it just fine.

+4
source

Source: https://habr.com/ru/post/1270425/


All Articles