A guard is an object that automatically performs clean-up actions when it goes out of scope. When copying the responsibility to perform the clean-up actions is transferred to the target (left hand side) object. On assignment frist any pending clean-up actions are done and then the ownership for the clean-up actions is transferred.
class Locker { public: // Initialize the unlock object: Locker() : unlock_(&mutex_); // Issue a guard: Guard mkGuard() { bool locked = (0 == mutex_.trylock()); Guard g(&unlock_, locked); return g; } private: Mutex mutex_; // protecting mutex MutexUnlock unlock_; // unlock the mutex }; void foo() { Guard g = theLocker().mkGuard(); if (g.isLoaded()) { // Save access to locked resource. } else { // Error: can not lock resource. } }
Definition at line 105 of file guard.h.
OSB_LIB::Guard::Guard | ( | Cleanup * | pCleanup = 0 , |
|
bool | doClean = true | |||
) |
Create a (empty) guard.
When used as default constructor, i.e., without providing an Cleanup object, the guard behaves as if it was in charge for the clean-up. This specification allows to test the correct usage of the guard when copied or assigned.
pCleanup | Object to perform the clean-up actions, the guard does not take its ownership. | |
doClean | Flag if clean-up actions are to be performed. |
OSB_LIB::Guard::Guard | ( | Cleanup::AutoPtr | cleanup, | |
bool | doClean | |||
) |
Create a guard, taking ownership of the Cleanup object.
cleanup | Auto pointer to the Cleanup object, the guard takes ownership. | |
doClean | Flag if clean-up actions are to be performed. |
When working with mutexes, `doClean' should be set to true if caller of the guard constructor is owner of mutex lock, else false.
OSB_LIB::Guard::~Guard | ( | ) |
OSB_LIB::Guard::Guard | ( | Guard & | rhs | ) |
Non-const copy constructor.
Transfers the ownership of the clean-up actions and Cleanup object from `rhs'.
OSB_LIB::Guard::Guard | ( | GuardRef | r | ) |
std::pair<bool, int> OSB_LIB::Guard::cleanup | ( | ) |
Do the clean-up actions.
Calls pCleanup_->cleanup() if release() returns true and pCleanup_ is not NULL.
bool OSB_LIB::Guard::isLoaded | ( | ) | const [inline] |
bool OSB_LIB::Guard::release | ( | ) |
Release clean-up responsibility without calling pCleanup_->cleanup().
bool OSB_LIB::Guard::delCleanup_ [private] |
bool OSB_LIB::Guard::doClean_ [private] |
Cleanup* OSB_LIB::Guard::pCleanup_ [private] |