/*! * @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 = 0) // allocate a new counter : itsCounter(0) { 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; }; X& operator*() const { return *itsCounter->ptr; } X* operator->() const { return itsCounter->ptr; } X* get() const { return itsCounter ? itsCounter->ptr : 0; } bool unique() const { return (itsCounter ? itsCounter->count == 1 : true); } virtual unsigned int count() const { return (this->itsCounter ? itsCounter->count : 0); } private: struct counter { counter(X* p = 0, 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 = 0; } } }; #endif /* _COUNT_POINTER_H */