#pragma once#include<iostream> #include <string>using namespace Std;template<typename t>class smartpointer{//does not allow the use of Smartpointer sp=new T () so that only another SP object and constructor method can be assigned to the SP public:smartpointer (t* p = 0):p tr (p), ref_ Count (new size_t)//constructor {if (ptr) *ref_count = 1;} Smartpointer (smartpointer& src)//copy constructor {if (this! = &src) {ptr = Src.ptr;ref_count = Src.ref_count; (*ref_count) ++;}} t& operator* ()//operator overload, note the return type {if (PTR) return *ptr;//throw exception;} t* operator-> ()//operator overload, note the return type {if (PTR) return Ptr;//throw exception;} smartpointer& operator= (smartpointer& src)//operator overload, note the return type {if (this = = &SRC) return *this;releasecount (); ptr = Src.ptr;ref_count = Src.ref_count; (*ref_count) ++;return *this;} int Getrefcount () {return *ref_count;} Returns the Count value ~smartpointer () {Releasecount ();} destructor private:t* ptr;size_t* ref_count;void releasecount ()//Count minus one, if minus one after 0, free memory {if (PTR &&-(*ref_count) = = 0) { Delete Ptr;delete ref_count;}}; void Main () {smartpointer<string> CP1 (New StriNg ("a")), cout << *cp1 << endl;cout << cp1->size () << Endl; Smartpointer<string> cp2 (CP1) cout << *cp1 << endl;cout << cp1->size () << endl;cout << cp1.getrefcount () << Endl; smartpointer<string> CP3;CP3 = CP2;CP3 = CP1;CP3 = Cp3;cout << cp3.getrefcount () << Endl; Smartpointer<string> CP4 (New string ("B")) CP3 = Cp4;cout << cp1.getrefcount () << endl;system ("Pause" );}
A smart pointer based on reference counting