#include #include using namespace std; /* * Implementing shared_ptr using unique_ptr! */ template class smart_ptr { /* * First we need an auxiliary class to hold the pointer * and a count of references to it. */ template class smart_ptr_aux { unique_ptr ap; int count = 1; public: smart_ptr_aux(Tprime *p) : ap(p) {} T *get() const {return ap.get();} /* * The functions increment and decrement adjust the count, * deleting the object pointed to and this auxiliary object when * the count falls to zero. The decrement function must be static * in order to delete the object p. The increment function is made * static for consistency. */ static void decrement(smart_ptr_aux *aux) { aux->count--; cerr << "dec:Used " << aux->count << " times\n"; if (aux->count == 0) { delete aux; cerr << "dec:Deleted managed object\n"; } } static void increment(smart_ptr_aux *aux) { aux->count++; cerr << "inc:Used " << aux->count << " times\n"; } }; /* * Now the smart pointer class itself uses the inc/dec methods in * its constructors, destructors, and assignment operator. */ smart_ptr_aux *field; public: smart_ptr( T *p ) : field(new smart_ptr_aux(p)) {} ~smart_ptr() { smart_ptr_aux::decrement(field); } smart_ptr(const smart_ptr & p) : field(p.field) { smart_ptr_aux::increment(field); } smart_ptr& operator=(const smart_ptr & other) { if (&other != this) { smart_ptr_aux::decrement(field); field = other.field; smart_ptr_aux::increment(field); } return *this; } T &operator*() { return *(field->get()); } T *operator->() const { return field->get(); } }; int main() { int *ip = new int(13); smart_ptr sp1(ip); { auto sp2(sp1); cerr << "sp2:Value is " << *sp2 << endl; } cerr << "sp1:Value is " << *sp1 << endl; return 0; }