title: 智能指针的简单实现
date: 2022-05-06 09:31:04
tags: [智能指针]
categories: [c++]
我的个人博客
shared_ptr的简单实现(非线程安全)
主要包括以下成员函数:
-
构造函数
-
析构函数
-
拷贝构造函数
-
operator=()
-
operator*()
-
operator->()
#include#include using namespace std; template class shared_ptr{ private: size_t* p_count; T* ptr; public: explicit shared_ptr(T* _ptr = nullptr):ptr(_ptr){ if(ptr) p_count = new size_t(1); else p_count = new size_t(0); } shared_ptr(const shared_ptr & rhs){ ptr = rhs.ptr; p_count = rhs.p_count; (*p_count)++; } shared_ptr & operator=(const shared_ptr & rhs){ if(this == &rhs) return *this; if(ptr){ (*p_count)--; if((*p_count)==0){ delete ptr; delete p_count; } } ptr = rhs.ptr; p_count = rhs.p_count; (*p_count)++; return *this; } T& operator*(){ assert(ptr); return *ptr; } T* operator->(){ assert(ptr); return ptr; } size_t use_count() const { return *p_count; } ~shared_ptr(){ (*p_count)--; if((*p_count)==0){ delete ptr; delete p_count; } } }; class test{ public: int a = 1; }; int main(){ shared_ptr p1(new test); // 默认构造函数 cout< a< p2(p1); // 拷贝构造函数 cout<<"p2:"< p3 = p2; // 拷贝构造函数 cout<<"p2:"< p4(new test); cout<<"Before p4:"< unique_ptr的简单实现 主要包括一下成员函数:
构造函数;
移动构造函数;
析构函数;
禁用拷贝构造函数;
禁用拷贝赋值函数 operator=();
reset(): 释放源资源,指向新资源;
release(): 返回资源,放弃对资源的管理;
get(): 返回资源,只是公外部使用,依然管理资源;
operator bool(): 是否持有资源;
operator*();
operator->();
#include#include template class unique_ptr{ private: T* ptr; public: unique_ptr(T* _ptr):ptr(_ptr){}; unique_ptr(unique_ptr&& rhs):ptr(rhs.release()){}; ~unique_ptr(){ if(ptr) delete ptr; ptr = nullptr; } unique_ptr(const unique_ptr& rhs) = delete; unique_ptr& operator=(const unique_ptr& rhs) = delete; public: void reset(T* _ptr){ if(ptr) delete ptr; ptr = _ptr; } T* release(){ T* pTemp = ptr; ptr = nullptr; return pTemp; } T* get(){ return ptr; } public: explicit operator bool() const{ return ptr != nullptr; } T& operator*(){ assert(ptr); return *ptr; } T* operator->(){ assert(ptr); return ptr; } }; class test{ public: int a = 1; }; int main(){ unique_ptr x(new test); cout<<"x->a:"<<(*x).a< y = move(x); //test* aaa = x.get(); if(!x) cout<<"Moved x!!"< a:"< a< 参考文献:
[1] https://zhuanlan.zhihu.com/p/344953368
[2] https://www.ccppcoding.com/archives/202



