Programmer's Wiki
Advertisement

Guard is a simple class which work in languages that supports the Resource Acquisition Is Initialization approach (RAII). Guard used to be used specially on semafor like locks. The basic idea is that we acquire the lock with declaring a variable inside a scope or object and we release it when the block ends or the object dies.

Example[]

Let us have a Lock class which has Acquire() and Release() methods.

In Java (without Guard)[]

try {
  lock.Acquire();
  // do something dangerous;
} finally {
  lock.Release();
}

or

try {
  lock.Acquire();
  // do something dangerous;
} catch (Exception e)
{
  // do some error handling
} finally {
  lock.Release();
}

In C++ (with Guard)[]

Guard g(lock);
// do something dangerous

or

Guard g(lock);
try {
  // Do something dangerous
} catch (Exception e)
{
  // do some error handling
}

Implementation[]

C++[]

class Guard {
    Guard(Lock& lock_)
    : lock(lock_)
    {
        lock.Acquire();
    }
    ~Guard()
    {
        lock.Release();
    }
private:
    Guard(const Guard&)
    void operator=(const Guard&)

    Lock &lock;
};
Advertisement