#ifndef PTR_H #define PTR_H #include template class Ptr{ public: Ptr(T * pek = 0) throw(std::bad_alloc); Ptr(const Ptr& other) throw(); ~Ptr() throw(); const Ptr& operator=(const Ptr& other); T& operator*(); const T& operator*() const; T* operator->(); const T* operator->() const; bool operator==(const Ptr& other) const; bool operator!=(const Ptr& other) const; operator T*() const throw(); template operator Ptr(); private: T * pointer; int * count; template friend class Ptr; Ptr(T *p, int *c); }; template Ptr::Ptr(T *pek) throw(std::bad_alloc): pointer(pek), count((pointer)?new int(1):0){} template Ptr::Ptr(const Ptr& other) throw(): pointer(other.pointer), count(other.count){ if (pointer) (*count)++; } template Ptr::Ptr(T *p, int *c): pointer(p), count(c){ if (pointer) (*count)++; } template Ptr::~Ptr() throw(){ if (pointer && --*count == 0){ delete count; delete pointer; } } template const Ptr& Ptr::operator=(const Ptr& other){ if (pointer != other.pointer){ if (pointer && --*count == 0){ delete count; delete pointer; } pointer = other.pointer; count = other.count; if (pointer) ++*count; } return * this; } template T& Ptr::operator*(){ return *pointer; } template const T& Ptr::operator*() const{ return *pointer; } template T* Ptr::operator->(){ return pointer; } template const T* Ptr::operator->() const{ return pointer; } template bool Ptr::operator==(const Ptr& other) const{ return pointer == other.pointer; } template bool Ptr::operator!=(const Ptr& other) const{ return pointer != other.pointer; } template template Ptr::operator Ptr(){ return Ptr(pointer, count); } template Ptr::operator T*() const throw(){ return pointer; } #endif