一篇文章带你搞定手写shared_ptr智能指针
主要就是个引用计数的思想,在构造函数的地方加一,拷贝构造函数的时候建议,但是rhs要加一计数。
#include <iostream> using namespace std; class share_count{ public: share_count():m_count(1){} void add_count(){ ++m_count; } long reduce_count() { --m_count; return m_count; } long get_count()const { return m_count;} private: long m_count; }; template<typename T> class shared_ptr{ public: // shared_ptr() : m_ptr(nullptr) {} shared_ptr(T *ptr = nullptr) : m_ptr(ptr) { cout << "ctor" << endl; if (m_ptr) { m_count = new share_count(); } } shared_ptr(const shared_ptr &rhs) noexcept { // cout << "cptor" << endl; if(m_ptr != nullptr) this->~shared_ptr(); cout << &rhs << endl; m_ptr = rhs.m_ptr; m_count = rhs.m_count; m_count->add_count(); // cout << m_count->get_count() << endl; } shared_ptr &operator=(const shared_ptr &rhs) noexcept { // cout << "operator =" << endl; if (m_ptr != nullptr) this->~shared_ptr(); cout << &rhs << endl; m_ptr = rhs.m_ptr; m_count = rhs.m_count; m_count->add_count(); // cout << m_count->get_count() << endl; return *this; } T& operator*()const { return *m_ptr;} T* operator->()const{return m_ptr;} operator bool() const { return m_ptr;} ~shared_ptr() { if(m_count != nullptr && m_ptr != nullptr){ m_count->reduce_count(); if (m_count->get_count() == 0) { cout << "~shared_ptr()" << endl; delete m_ptr; delete m_count; m_ptr = nullptr; m_count = nullptr; } } } long get_count() const { return m_count->get_count(); } private: T* m_ptr = nullptr; share_count *m_count = nullptr; }; int main(){ shared_ptr<string> ptr_2(new string("Hello!")); // shared_ptr<string> ptr_3(ptr_2); // shared_ptr<string> ptr_4 = ptr_2; // cout << *ptr_3 << endl; // cout << *ptr_4 << endl; shared_ptr<string> ptr_5 = ptr_2; shared_ptr<string> ptr_6; ptr_6 = ptr_2; return 0; }#笔试#