Mutable and Volatile Keywords
I've seen mutable used only a few times, and not thought much about it until recently went I was reading about what it does on MSDN. This keyword makes a variable ignore whether a function is const or not within a class.
Below is an example of one way it could be used.
class MyClass
{
//
// Functions
public:
//
MyClass()
:
m_value( 10 ),
m_valueGetCount( 0 )
{
}
//
int GetValue() const
{
// Class variable can be changed despite function being declared const
++m_valueGetCount;
return m_value;
}
//
unsigned int ValueGetCount() const
{
return m_valueGetCount;
}
//
// Attributes
private:
int m_value;
mutable unsigned int m_valueGetCount;
};
My experiences with it have been for thread synchronization objects I use such as my Semaphore class. For some reason the MacOSX implementation of the semaphore doesn't allow me to get the count, so I had to add a variable myself.
The mutable keyword allowed me to keep the class usable within a const scope, which the use of const_cast().
Another keyword I seem to use with threads a lot is volatile. It prevents variable value being cached, forcing it be read from memory every single time it is access.
//
//
namespace
{
volatile bool l_myBoolean = true;
}
//
//
void main()
{
//
createSomeOtherThread();
//
while( l_myBoolean )
{
// do nothing
}
}
//
//
int someOtherThread( void * inParam )
{
l_myBoolean = false;
return 0;
}
In the case of a while loop that relies on a boolean that gets updated in another thread, this has the potentially that the compiler will cache it and thus the loop will never end.


