September 93 - CHLockSaver
CHLockSaver
Michael D. Rossetti
Here's a great gift idea for that special person in your life: you! I'll bet that everyone out in that reading audience can use this terrific labor saving device right this very evening: automatically unlocking handles and resources! That's right-you'll never have to worry about balancing your HLocks with HUnlocks ever again! And if you read on you'll see how you can get two additional special gifts for no extra charge: Magic Object Lockers and Charmed Resource Unpurgers.
Using secret C++ technology [constructors and destructors] our scientists [me] have labored for many years [not!] to develop the following class:
class CHLockSaver
{
public:
CHLockSaver(Handle aHandle)
: fLockedHandle(aHandle)
{ fOldState = HGetState(aHandle);
HLock(aHandle); }
~CHLockSaver()
{ HSetState(fLockedHandle, fOldState); }
protected:
Handle fLockedHandle;
SignedByte fOldState;
};
To lock a handle simply use a statement like:
CHLockSaver myLocker(myHandle);
(Note: CHLock is pronounced like schlock [so if you use this stuff you can justifiably call yourself a CHLockMeister].)
Like magic you handle gets locked [it's all in the constructor], your countertops shine like new, and…presto…when "myLocker" goes out of scope "myHandle" is restored magically [okay, it's all in the destructor] to its original state.
As promised, here's a couple of free classes which work just like the CHLockSaver. Here's one which will lock down a derivative of TObject:
class COLockSaver
{
public:
COLockSaver(TObject* anObject)
: fLockedObject(anObject)
{ fOldState = anObject->Lock(TRUE); }
~COLockSaver()
{ fLockedObject->Lock(fOldState); }
protected:
TObject* fLockedObject;
Boolean fOldState;
};
Here's another class which makes a resource unpurgeable:
class CHPurgeSaver
{
public:
CHPurgeSaver(Handle aResource)
: fUnpurgedHandle(aResource)
{ fOldState = HGetState(aResource);
HNoPurge(aResource); }
~CHPurgeSaver()
{ HSetState(fUnpurgedHandle, fOldState); }
protected:
Handle fUnpurgedHandle;
SignedByte fOldState;
};
Caveat Emptor: CHLockSaver and CHPurgeSaver completely restore the handle's state to its original settings-any state changes which you make before CHLockSaver and CHPurgeSaver go out of scope will be lost.