C++ volatile member functions

0xbadf00d picture 0xbadf00d · Jan 28, 2011 · Viewed 23.1k times · Source
class MyClass
{
    int x, y;
    void foo() volatile {
        // do stuff with x
        // do stuff with y
    }   
};

Do I need to declare x and y as volatile or will be all member variables treated as volatile automatically?

I want to make sure that "stuff with x" is not reordered with "stuff with y" by the compiler.

EDIT: What happens if I'm casting a normal type to a volatile type? Would this instruct the compiler to not reorder access to that location? I want to pass a normal variable in a special situation to a function which parameter is volatile. I must be sure compiler doesn't reorder that call with prior or followed reads and writes.

Answer

templatetypedef picture templatetypedef · Jan 28, 2011

Marking a member function volatile is like marking it const; it means that the receiver object is treated as though it were declared as a volatile T*. Consequentially, any reference to x or y will be treated as a volatile read in the member function. Moreover, a volatile object can only call volatile member functions.

That said, you may want to mark x and y volatile anyway if you really do want all accesses to them to be treated as volatile.