shared_ptr实现
参考文献:
http://blog.leanote.com/post/shijiaxin.cn@gmail.com/C-shared_ptr
https://www.cnblogs.com/wxquare/p/4759020.html
#include <iostream> #include <memory> using namespace std; class Delete { public: template <typename T> void operator()(T *p) const { delete p; } }; template<typename T> class my_shared_ptr { public: T* _ptr; size_t* _count; size_t* _weak_count; void clear() { if(this->_ptr != nullptr) { (*this->_count)--; if (*this->_count == 0) { delete this->_ptr; delete this->_count; this->_ptr = nullptr; this->_count = nullptr; } } } public: my_shared_ptr(T* ptr = nullptr) : _ptr(ptr) { if (_ptr) { _count = new size_t(1); _weak_count = new size_t(0); } else { _count = new size_t(0); _weak_count = new size_t(0); } } my_shared_ptr(const my_shared_ptr& ptr) { if (this != &ptr) { this->_ptr = ptr._ptr; this->_count = ptr._count; (*this->_count)++; } } my_shared_ptr& operator=(const my_shared_ptr& ptr) { if (this->_ptr == ptr._ptr) { return *this; } clear(); this->_ptr = ptr._ptr; this->_count = ptr._count; (*this->_count)++; return *this; } T& operator*() { return *(this->_ptr); } T* operator->() { return this->_ptr; } ~my_shared_ptr() { clear(); } size_t use_count(){ return *this->_count; } }; template <typename T> class my_weak_ptr { void clear() { if (_ptr == nullptr) return; _weak_count--; if (_count == 0 && _weak_count == 0) { delete _ptr; delete _count; delete _weak_count; } _count = nullptr; _weak_count = nullptr; _ptr = nullptr; } public: my_weak_ptr() { _count = nullptr; _ptr = nullptr; _weak_count = nullptr; } my_weak_ptr(const my_shared_ptr<T> &ptr) { _count = ptr._count; _ptr = ptr._ptr; _weak_count = ptr._weak_count; if (ptr._ptr == nullptr) return; _weak_count++; } my_weak_ptr<T> &operator=(const my_shared_ptr<T> &ptr) { clear(); if (ptr._ptr == nullptr) return *this; _count = ptr._count; _weak_count = ptr._weak_count; _ptr = ptr._ptr; _weak_count++; return *this; } size_t* _count; size_t* _weak_count; T* _ptr; my_shared_ptr<T> lock() { my_shared_ptr<T> tmp; if (_count == nullptr || _count == 0) { return tmp; } tmp._count = _count; tmp._ptr = _ptr; tmp._weak_count = _weak_count; _weak_count++; return tmp; } }; class myClass { public: my_weak_ptr<myClass> parent; my_shared_ptr<myClass> child; string name; myClass(string name) : name(name) { cout << "Create " << name << endl; }; ~myClass() { cout << "Delete " << name << endl; } }; int main() { my_shared_ptr<myClass> p1(new myClass("a")); my_shared_ptr<myClass> p2(new myClass("bb")); my_shared_ptr<myClass> p3 = p1; cout<<p1.use_count()<<endl; p1->child = p2; p2->parent = p1; auto ptr = p2->parent.lock(); cout << ptr->name << endl; }