1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107
|
/*
** Copyright 2002, Double Precision Inc.
**
** See COPYING for distribution information.
*/
#ifndef libmail_objectmonitor_H
#define libmail_objectmonitor_H
///////////////////////////////////////////////////////////////////////////
//
// Helper class that detects when the object references by a ptr is destroyed.
//
// Subclass mail::obj. Declare mail::ptr<T>, where T is mail::obj's
// subclass. After mail::obj is destroyed, mail::ptr<T>::operator T *()
// will return NULL
#include <set>
#include <cstdio>
#include "namespace.H"
LIBMAIL_START
class ptrBase {
public:
ptrBase();
virtual ~ptrBase();
virtual void ptrDestroyed()=0;
};
template<class T> class ptr : public ptrBase {
T *r;
public:
ptr(T *ptrArg) : r(NULL)
{
if (ptrArg)
ptrArg->objectBaseSet.insert(this);
r=ptrArg;
}
ptr(const ptr &o) : r(NULL)
{
(*this)=o;
}
ptr &operator=(const ptr &o)
{
if (o.r == NULL ||
o.r->objectBaseSet.count(this) == 0)
{
if (o.r)
o.r->objectBaseSet.insert(this);
if (r && r->objectBaseSet.count(this) > 0)
r->objectBaseSet.erase(r->objectBaseSet
.find(this));
}
r=o.r;
return *this;
}
~ptr()
{
if (r && r->objectBaseSet.count(this) > 0)
r->objectBaseSet.erase(r->objectBaseSet.find(this));
}
operator T *() const
{
return r;
}
T * operator->() const
{
return r;
}
bool isDestroyed() const { return r == 0; }
void ptrDestroyed() { r=NULL; }
};
// Some convenient macros
#define MONITOR(T) mail::ptr<T> thisMonitor(this)
#define DESTROYED() ( thisMonitor.isDestroyed() )
class obj {
public:
std::set<ptrBase *> objectBaseSet;
obj();
virtual ~obj();
obj(const obj &);
obj &operator=(const obj &);
};
LIBMAIL_END
#endif
|