Smart pointer class that can share the pointer with sibling objects
A simple smart pointer that uses reference counting to manage a resource:
// Keeps track of the reference count for a shared object. struct RefCount { int ref_count_; RefCount () : ref_count_ (0) { } RefCount (int i) : ref_count_ (i) { } }; // Smart pointer class that can share the pointer with // sibling objects. template class SharedPtr { public: SharedPtr () : pointer_ (NULL), ref_count_ (NULL) { } SharedPtr (T* t) : pointer_ (t), ref_count_ (new RefCount ()) { } SharedPtr (const SharedPtr& sp) { pointer_ = sp.pointer_; ref_count_ = sp.ref_count_; ++ref_count_->ref_count_; } ~SharedPtr () { if (ref_count_->ref_count_ == 0) { delete pointer_; delete ref_count_; } else --ref_count_->ref_count_; } T& operator* () const { return *pointer_; } T* operator-> () const { return pointer_; } SharedPtr* operator= (const SharedPtr& sp) { pointer_ = sp.pointer_; ref_count_ = sp.ref_count_; ++ref_count_->ref_count_; } private: T* pointer_; RefCount* ref_count_; };
Example usage:
class Test { public: Test (int id) : id_ (id) { } int id () const { return id_; } ~Test () { std::cout << "deleted" << std::endl; } private: int id_; }; static SharedPtr<Test>* SP = new SharedPtr<Test> (); static void test1 (SharedPtr<Test> sp) { SharedPtr<Test> sp1 (new Test (1001)); std::cout << sp1->id () << '\n'; // => 1001 sp = sp1; *SP = sp1; std::cout << "leaving test1 " << std::endl; } int main () { SharedPtr<Test> sp; test1 (sp); std::cout << (*sp).id () << '\n'; // => 1001 std::cout << "leaving main " << std::endl; delete SP; return 0; }