Home > Blogs > 30 C++ Tips in 30 Days: Tip # 16 declare volatile member functions for volatile objects

30 C++ Tips in 30 Days: Tip # 16 declare volatile member functions for volatile objects

By  Dec 6, 2007

Topics: Programming, C/C++

If your objects are used in a multithreaded environment or they can be accessed asynchronously (say by a signal handler), they should be declared volatile. That means you should also declare at least some of their member functions volatile too.
A volatile object can call only volatile member functions safely. If the program calls a member function that isn't volatile, its behavior is undefined. Most compilers issue a warning if a non-volatile member function is called by a volatile object:

struct S
{
 int f1();
 int f2() volatile;
}; 

volatile S s;
s.f1(); //compilation error, f1 isn't volatile
s.f2(); //OK

Whether the object is volatile or not, calling a volatile member function is always safe, although it might incur performance overhead so there's no point in declaring every member function as volatile: 

S s2;
s2.f2(); //safe, though possible less efficient

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.

Other Things You Might Like

Xamarin Unleashed

Xamarin Unleashed