当前位置: 代码迷 >> 综合 >> C++自定义智能指针——shared_ptr
  详细解决方案

C++自定义智能指针——shared_ptr

热度:67   发布时间:2024-02-08 02:58:39.0

最近在找工作,发现许多公司在面试的时候会要求手写智能指针,因此自己参照的别人的博客在上面修改了一些,作为参考原文连接。shared_ptr通过引用计数来管理多个指针指向同一个对象,对计数器的操作要格外重视。

#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,则旧指针计数值-1if (*ref_count > 0)remove(); //旧对象的引用计数为1,删除旧对象//旧指针指向新对象ref = sptr.ref;ref_count = sptr.ref_count;++(*ref_count);//指针计数+1return *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(); //通过指针调用成员函数
}