#ifndef __SMARTPTR_H#define __SMARTPTR_Htemplate<class T>class smartptr{ public: // class typedefs and constants typedef T value_type; // constructor explicit smartptr(value_type* p = 0) : ptr(p), count(new long(1)) { } // copy constructor smartptr(const smartptr<value_type>& rhs) : ptr(rhs.ptr), count(rhs.count) { ++(*count); } // assignment operator for pointers template<class new_value_type> smartptr<value_type>& operator =(new_value_type* rhs) { if(ptr == rhs) { return *this; } _free(); // provide compile time type checking (looks ugly but it works) new_value_type *t2 = 0; value_type *t1 = t2; ptr = rhs; count = new long(1); return *this; } // assignment operator for smartptr's template<class T2> smartptr<T>& operator =(smartptr<T2>& rhs) { if(this == &rhs) { return *this; } // release smartptr _free(); // provide compile time type checking (looks ugly but it works) new_value_type *t2 = 0; value_type *t1 = t2; // assign the new smartptr assign_smartptr<value_type, new_value_type>(&count, reinterpret_cast<void**>(&ptr), &rhs); return *this; } // destructor ~smartptr() { _free(); } // returns the internal type as a reference value_type& operator *() { return *ptr; } // returns a pointer to the internal type value_type* operator->() { return static_cast<value_type*>(ptr); } // returns the current reference count for the object // being pointed to long refcount() const { return *count; } // release the smartptr void release() { _free(); } private: // called to decrement reference count and free memory if necessary void _free() { if(--(*count) == 0) { delete ptr; delete count; } // safety first ptr = 0; count = 0; } // give friendship to non-member template function template<class value_type, class new_value_type> friend void assign_smartptr(long** count, void** dest, smartptr<new_value_type>* src); // class data members T *ptr; long *count;};template<class value_type, class new_value_type>inline void assign_smartptr(long** count, void** dest, smartptr<new_value_type>* src){ *dest = src->ptr; *count = src->count; ++(**count);}#endif
I'm still looking for someone to test this code on another compiler (and platform).
Thanks again,
- Dire Wolf
direwolf@digitalfiends.com
Edited by - Dire.Wolf on September 7, 2000 2:30:39 PM
Edited by - Dire.Wolf on September 7, 2000 2:31:45 PM