Alex Rivera | Logout

when should a member function be both const and volatile together?

Asked 2009-03-17T16:36:33.163
11

I was reading about volatile member function and came across an affirmation that member function can be both const and volatile together. I didn't get the real use of such a thing. Can anyone please share their experience on practical usage of having member function as const and volatile together.

I wrote small class to test the same:

class Temp
{
public:

    Temp(int x) : X(x)
    {
    }

    int getX() const volatile
    {
        return X;
    }

    int getBiggerX()
    {
        return X + 10;
    }
private:
    int X;
};

void test( const volatile Temp& aTemp)
{
    int x = aTemp.getX();
}

int main(int argc, char* argv[])
{
    const volatile Temp aTemp(10);
    test(aTemp);

    return 0;
}
Edit
Report

1 Answer

17

The cv qualification distilled means:

I won't change the value, but there is something out there that can.

You are making a promise to yourself that you won't change the value (const qualification) and requesting the compiler to keep its slimy hands off of this object and turn off all optimization (volatile qualification). Unfortunately, there is little standard among the compiler vendors when it comes to treating volatile fairly. And volatile is a hint to the compiler after all.

A practical use case of this is a system clock. Supposing 0xDEADBEEF was your system specific address of a hardware clock register you'd write:

int const volatile *c = reinterpret_cast<int *>(0xDEADBEEF);

You can't modify that register value, but each time you read it, it is likely to have a different value.

Also, can use this to model UARTs.

answered 2009-03-17T16:40:32.903

Your Answer