Rajeshwar
Rajeshwar

Reputation: 11651

Member functions that are volatile and const

I came across this post this which attempts to explain volatile member functions and const volatile member functions. The top answerer stated

marking a member function as const or volatile (or a combined const volatile) applies those qualifiers to the this pointer used in the function

What does the above mean ? How does marking the this qualifier of a method as volatile or const volatile affect the this pointer?

I am confused what that would mean to the method(s) as such

class foo
{
   void someMethod() volatile 
   {std::cout << "volatile method" }

   void otherMethod() const volatile 
   {std::cout << "const volatile method"}
};

Upvotes: 1

Views: 133

Answers (1)

Mats Petersson
Mats Petersson

Reputation: 129374

If this is marked volatile, it will affect the compiler's ability to optimise away updates to/from the members pointed to by *this.

The TYPICAL use-case for volatile is where you have hardware registers - not particularly typical to use a class to describe hardware registers, but we can do it.

For example, one could have a class like this:

class my_hardware_device
{
  public:
    int32_t reg1; 
    int32_t reg2;
  private:
    int32_t reserved;
  public:
    int32_t reg4;
    int func() volatile;
};

volatile my_hardware_device hw1 = 
   reinterpret_cast<volatile my_hardware_device*>(0x10000000); 
...
int my_hardware_device::func() volatile
{ 
    reg2 = 3;
    reg3 = 8;
    reg2 = 7;
    if (reg2 == 4)
    {
       ...
    }
}

...
hw1->func();

Without volatile, the compiler could very well decide to remove the reg2 = 3 and determine that reg2 == 4 is always false, both because of reg2 = 7;. But since it's actually pointing at some hardware, it doesn't behave the way the compiler would expect. [This is a very silly example just constructed to show how it could work - I'm not by any means suggesting that this is a "correct" or "good" solution for any such hardware interface - never mind portability problems, and all manner of other things - and of course the vtable would cause complete havoc if you ever tried to use this with virtual functions - and if you are dealing with hardware in a driver, you probably do want vtables to solve hardware variants, giving yet another reason for implementing this sort of code in a different way.]

The const variant means that the compiler is not allowed to write to members of *this (in other words members in the class foo in your example), except if they are marked as mutable (or if a const_cast is used to cast away the constness - const_cast can also be used to cast away volatileness, by the way).

Combining the both const and volatile simply means that reads can not be optimised away, and the compiler is not allowed to update the members of *this.

Upvotes: 5

Related Questions