Below is a very simple example of a class. This class is used in a multi-threaded system and I want to ensure that every access to _x (also in a future extensions of the class by other developers) will be protected by mutex. One way doing so, is to put the mutex in the setter and getter and enforce using them also from the class methods, meaning, any direct access will generate a compilation error. Is it possible?
class Myclass
{
public:
int getX() const
{
boost::mutex::scoped_lock lock(_lock);
return _x;
}
void setX(int x)
{
boost::mutex::scoped_lock lock(_lock);
_x = x;
}
void foo()
{
//accessing _x;
}
private:
mutable boost::mutex _lock;
int _x;
};