智能指针shared_ptr的实现

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
class sharedPtr{
public:
    sharedPtr(){
        cout << "call default construct
";
    };
    sharedPtr(int *_next, int *_val):next(_next), val(_val){
        cout << "call sharedPtr construct
";
        *next = *next + 1;
        cout << "next = " << *next << endl;
    };
    sharedPtr(const sharedPtr &a){
        cout << "call sharedPtr copy construct
";
        if(this == &a)  return ;
        next = a.next;
        val = a.val;
        *next = *next + 1;
        cout << "next = " << *next << endl;
    };
    const sharedPtr& operator=(const sharedPtr &a){
        cout << "call sharedPtr operator =
";
        if(this == &a){
            return *this;
        }
        if(next != NULL){
            *next = *next - 1;
        }
        if(next != NULL && *next == 0){
            delete next;
            delete val;
        }
        next = a.next;
        val = a.val;
        *next = *next + 1;
        cout << "next = " << *next << endl;
        return *this;
    };
    ~sharedPtr(){
        *next = *next - 1;
        cout << "call sharedPre deconstruct
";
        if(*next == 0){
            cout << "call the true deconstruct
";
            delete next;
            delete val;
        }
    };
private:
    int *next;
    int *val;
};
int main(){
    int *a = new int(0);
    int *b = new int(9);
    sharedPtr *p1= new sharedPtr(a, b);
    sharedPtr *p2 = new sharedPtr(*p1);
    sharedPtr *p3 = new sharedPtr();
    *p3 = *p1;
    delete p1;
    delete p2;
    delete p3;
    return 0;
}
原文地址:https://www.cnblogs.com/qq136155330/p/12738852.html