/*! * @file count_pointer.h Contains the Counted Pointer Class, that points to Member-Objects. */ #ifndef _COUNT_POINTER_H #define _COUNT_POINTER_H template class CountPointer { public: explicit CountPointer(X* p = NULL) // allocate a new counter : itsCounter(NULL) { if (p) itsCounter = new counter(p); } virtual ~CountPointer() { release(); } CountPointer(const CountPointer& r) { acquire(r.itsCounter); } CountPointer& operator=(const CountPointer& r) { if (this != &r) { release(); acquire(r.itsCounter); } return *this; } bool operator==(const CountPointer& r) const { return this->itsCounter->ptr == r.itsCounter->ptr; }; inline X& operator*() const { return *itsCounter->ptr; } inline X* operator->() const { return itsCounter->ptr; } inline bool unique() const { return (itsCounter ? itsCounter->count == 1 : true); } inline bool isNull() const { return (!itsCounter); } virtual unsigned int count() const { return (this->itsCounter ? itsCounter->count : 0); } private: struct counter { counter(X* p = NULL, unsigned c = 1) : ptr(p), count(c) {} X* ptr; unsigned count; } * itsCounter; void acquire(counter* c) { // increment the count itsCounter = c; if (c) ++c->count; } void release() { // decrement the count, delete if it is 0 if (itsCounter) { if (--itsCounter->count == 0) { delete itsCounter->ptr; delete itsCounter; } itsCounter = NULL; } } }; #endif /* _COUNT_POINTER_H */