/* * SPtr.hpp * * Created on: Feb 25, 2016 * Author: mike */ #ifndef SPTR_HPP_ #define SPTR_HPP_ #include using namespace std; typedef double T; // Smart pointer class class SPtr { private: int* count; // shared object among all SPtr with same target T* target; // sharted target object // Make *this point to the same T object as p. void attach(SPtr& p); // Make *this no longer point to anything, and delete the count and target // if this was the last pointer to that object. void detach(); public: // Default constructor creates a new T and a new SPtr that "points" to it. SPtr() : count(new int), target(new T) { *count = 1; } // Destructor decrements pointer copy count. Deletes when count reaches 1 ~SPtr() { cout << "destructor called" << endl; detach(); } // Copy constructor. Creates another SPtr pointing to same object as its arg. SPtr(SPtr & p) { attach(p); } // Assignment operator. SPtr& operator=(SPtr & p) { detach(); // detach *this from the object it used to point to attach(p); // attach *this to p return *this; } // Follow operator. T & operator*() { return *target; } }; #endif /* SPTR_HPP_ */