Simple simulation for shared_ptr #include <iostream> #include <string.h>using namespace Std;class shared_ptr_ in the Boost library Rep{friend class Shared_ptr;public:shared_ptr_rep (const char *STR = ""): Count (0) {px = new Char[strlen (str) + 1];strcpy (p x, str);} ~shared_ptr_rep () {delete[]px;} Public:void increment () {count++;} void Decrement () {if (--count = = 0) {Delete this;//which rep has a count of 0 released at that time Rep}}char* get () {return px;} Private:char *px;int count;};/ Class Shared_ptr{public:shared_ptr (const Char *str = ""): Rep (new Shared_ptr_rep (str)) {rep->increment ();} shared_ptr (const shared_ptr &s): Rep (s.rep) {rep->increment ();} shared_ptr& operator= (const shared_ptr &s) {if (This! = &s) {rep->decrement (); Iterator rep = S.rep;rep->increment ();} return *this;} ~shared_ptr () {rep->decrement ();} public:char& operator* () {return * (REP->PX);} char* operator-> () {return rep->px;} Private:shared_ptr_rep *rep; };intMain () {char *p = new char (' a '); char *q = new char (' B '); shared_ptr s1 (p); cout << *s1 << endl;shared_ptr s2 = S1 ; cout << *s2 << endl;shared_ptr S3 (q); s3 = S2;cout << *s3 << endl;shared_ptr S4 (q); cout << * S4 << Endl;shared_ptr s5 = s4;cout << *s5 << endl;return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"C + +" Simple simulation realizes the shared-ptr under the Boost library