Smart Pointer class

Source: Internet
Author: User

Tag:c++    smart pointer class     smart pointer    

Smart pointer class//----------------------------------------//1. Cardinality is placed in the usage count class//actual class point-and usage count class-base data//Usage Count class u_ptr{ Friend class hasptr;//friend class int *ip;//This is the base to protect, according to size_t use; u_ptr (int *p): IP (P), use (1) {}~u_ptr () {delete ip;}}; Class hasptr//the actual class {public:hasptr (int *p,int i):p tr (New U_ptr ((p)), Val (i) {}hasptr (const hasptr &orig):p TR (orig.ptr ), Val (orig.val) {++ptr->use;} hasptr& operator= (const hasptr &RHS) {++rhs.ptr->use;if (--ptr->use = = 0) Delete ptr;ptr=rhs.ptr;val= Rhs.val;return *this;} ~hasptr () {if (--ptr->use = = 0) delete ptr;} Private:u_ptr *ptr;int val;};/ /----------------------------------------------//2. The base is placed in the actual class//the actual class points to the use of the Count class, the actual class also points to the same base data//Usage Count class U_ptr{friend Class hasptr;//friend class size_t use; U_ptr (): Use (1) {}~u_ptr () {}};class hasptr//actual class {public:hasptr (int *p,int i):p tr (new u_ptr), IP (p) val (i) {}hasptr (const Hasptr &orig):p tr (orig.ptr), IP (ORIG.P); Val (orig.val) {++ptr->use;} hasptr& operator= (const hasptr &RHS) {++rhs.ptr->use;if (--ptr->use = = 0) {Delete Ptr;deleTe IP;} Ptr=rhs.ptr;ip=rhs.ip;val=rhs.val;return *this;} ~hasptr () {if (--ptr->use = = 0) {delete ptr;delete IP;}} Private:int *ip;//This is to protect the base according to U_ptr *ptr;int val;};/ /When defining a value class//Copying an object, copy the base data pointed to by the pointer at the same time

Smart Pointer class

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.