A smart pointer based on reference counting

Source: Internet
Author: User
Tags throw exception

#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 = = &AMP;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

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.