share_ptr 简单实现:
#include <iostream> using namespace std; template<class T> class SmartPtr { public: SmartPtr(T* ori_ptr); ~SmartPtr(); SmartPtr(SmartPtr<T>& ori_ptr); SmartPtr<T>& operator=(const SmartPtr<T>& ori_ptr); private: T* ptr; int* count; }; template<class T> SmartPtr<T>::SmartPtr(T* ori_ptr) { count = new int(1); ptr = ori_ptr; } template<class T> SmartPtr<T>::~SmartPtr() { if (--(*count) <= 0) { delete ptr; delete count; ptr = nullptr; count = nullptr; cout << "object was destroied" << endl; } } template<class T> SmartPtr<T>::SmartPtr(SmartPtr<T>& ori_ptr) { ++(*ori_ptr.count); ptr = ori_ptr.ptr; count = ori_ptr.count; } // 赋值运算符比较特殊,因为左边操作数本来可能已经指向了另外一个对象 // 所以在给左边智能指针赋值时,其所指向的对象应该被析构,所以要加一个判断,是否应该析构左边指针的原对象 template<class T> SmartPtr<T>& SmartPtr<T>::operator=(const SmartPtr<T>& ori_ptr) { ++(*ori_ptr.count); if (--(*count) <= 0) // 释放左边智能指针管理的原对象 { delete ptr; delete count; cout << " origin object destroied " << endl; } ptr = ori_ptr.ptr; count = ori_ptr.count; return *this; } int main() { SmartPtr<int> smartPtr1(new int(1)); SmartPtr<int> smartPtr11(smartPtr1); SmartPtr<int> smartPtr2(new int(2)); smartPtr2 = smartPtr1; return 0 }
weak_ptr简单实现: