自定义C++智能指针

 

 

#include<iostream>
using namespace std;
//自定义智能指针
template <class T> class SmartPointer {
public:
    SmartPointer(T* ptr) {
        ref = ptr;
        ref_count = new unsigned;
        *ref_count = 1;
    }

    //指针拷贝构造函数,新建一个指向已有对象的智能指针
    SmartPointer(SmartPointer<T>& sptr) {
        ref = sptr.ref;
        ref_count = sptr.ref_count;
        ++(*ref_count);
    }


//rewrite "=",修改指针的指向 SmartPointer<T>& operator = (SmartPointer<T>& sptr) { //同一个指针,直接返回 if (this == &sptr) return *this; //如果计数值大于1,则旧指针计数值-1 if (*ref_count > 0) remove(); //旧对象的引用计数为1,删除旧对象 //旧指针指向新对象 ref = sptr.ref; ref_count = sptr.ref_count; ++(*ref_count);//指针计数+1 return *this; } ~SmartPointer() { remove(); }
T
& operator*() { return *ref; } T* operator->() { return ref; } T getCount() { return static_cast<T>(*ref_count); } protected: //删除指针 void remove() { --(*ref_count); //如果计数值等于0,则销毁对象,执行析构函数 if (*ref_count == 0) { delete ref; delete ref_count; ref = NULL; ref_count = NULL; } }
private: unsigned* ref_count; //引用计数,定义为指针,是为了让所有指向同一对象的智能指针共享一个计数器 T* ref; //普通指针 }; class A { public: A() { cout << "A::A()" << endl; } ~A() { cout << "A::~A()" << endl; } void fun() { cout << "A::fun()" << endl; } }; int main() { SmartPointer<A> temp(new A()); (*temp).fun(); //通过对象调用成员函数 temp->fun(); //通过指针调用成员函数 }

 

 


原文链接:https://blog.csdn.net/weixin_44266215/article/details/107870594

posted on 2021-03-31 13:28  回形针的迷宫  阅读(148)  评论(0编辑  收藏  举报

导航