#ifndef RCPOINTE_H #define RCPOINTE_H #include #if defined(RCPOINTER_TESTDLL) #define RCPOINTER_CLASS class #elif defined (RCPOINTER_BUILDDLL) #define RCPOINTER_CLASS class _export #else #define RCPOINTER_CLASS class _import #endif // RcPointer is a class that can be used to create counted // pointers to the class X. This class is intialized with // a pointer to X, but acts as a proxy for that pointer. // It is responsible for keeping track of the number of objects // and functions actively looking at the pointer. When the // number of users is zero, the pointer is deleted. template RCPOINTER_CLASS RcPointer { public: RcPointer():stor(NULL){} RcPointer(X *p):stor(new Stor(p)){} RcPointer(const RcPointer &b) {if ((stor = b.stor)!=NULL) stor->rc++;} const RcPointer& operator = (const RcPointer &b) { if (b.stor) b.stor->rc++; free(); stor = b.stor; return *this; } ~RcPointer(){free();} X& operator [](int i){return (stor->pval)[i];} X* operator ->() {if (!stor) throw "Pointer not initialized"; return stor->pval;} X& operator*() {if (!stor) throw "Pointer not initialized"; return *(stor->pval);} X* operator ->()const {if (!stor) throw "Pointer not initialized"; return stor->pval;} X& operator*()const {if (!stor) throw "Pointer not initialized"; return *(stor->pval);} operator const void*() const {return stor ? this : 0;} protected: RCPOINTER_CLASS Stor { public: unsigned long int rc; X *pval; Stor(X *px):rc(1),pval(px){} ~Stor(){delete pval;} }; void free() {if(stor && --stor->rc == 0) delete stor;} Stor *stor; }; #endif