Fandom

Programmer's Wiki

Guard

407pages on
this wiki
Add New Page
Talk0 Share

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.

ExampleEdit

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

In Java (without Guard)Edit

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)Edit

Guard g(lock);
// do something dangerous

or

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

ImplementationEdit

C++ Edit

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

    Lock &lock;
};

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.