"C + +" Simple simulation realizes the shared-ptr under the Boost library

Source: Internet
Author: User

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-&GT;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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.