手动实现智能指针
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| template <typename T> class smart_ptr { public: explicit smart_ptr(T* ptr = nullptr) : ptr_(ptr) {} ~smart_ptr() { delete ptr_; } T* get() const { return ptr_; } T& operator*() const { return *ptr_; } T* operator->() const { return ptr_; } operator bool() const { return ptr_; } smart_ptr(smart_ptr& other) { ptr_ = other.release(); } smart_ptr& operator=(smart_ptr& rhs) { smart_ptr(rhs).swap(*this); return *this; } T* release() { T* ptr = ptr_; ptr_ = nullptr; return ptr; } void swap(smart_ptr& rhs) { using std::swap; swap(ptr_, rhs.ptr_); } private: T* ptr_; };
|
智能指针的理解:就是通过被管理类的实例去构造一个管理的类,意思就是:老子[程序员]不想管了,你来帮我管好它
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| class shared_count { public: shared_count() : count_(1) {} void add_count() { ++count_; } long reduce_count() { return --count_; } long get_count() const { return count_; } private: long count_; };
template <typename T> class smart_ptr { public: explicit smart_ptr(T* ptr = nullptr) : ptr_(ptr) { if (ptr) { shared_count_ = new shared_count(); } } ~smart_ptr() { if (ptr_ &&!shared_count_->reduce_count()) { delete ptr_; delete shared_count_; } } template <typename U> smart_ptr(const smart_ptr<U>& other) { ptr_ = other.ptr_; if (ptr_) { other.shared_count_->add_count(); shared_count_ = other.shared_count_; } } template <typename U> smart_ptr(smart_ptr<U>&& other) { ptr_ = other.ptr_; if (ptr_) { shared_count_ = other.shared_count_; other.ptr_ = nullptr; } }
void swap(smart_ptr& rhs) { std::swap(ptr_, rhs.ptr_); std::swap(shared_count_,rhs.shared_count_); }
long use_count() const { if (ptr_) { return shared_count_ -> get_count(); } else { return 0; } }
private: T* ptr_; shared_count* shared_count_; };
|