翻看以前的代碼的時候發現一個shared_ptr的簡單實現。
我記得是網上的一篇例子(好像改了一點),但是又懶得找出處了 ╮(╯▽╰)╭。
覺得這份代碼足以用來初步了解shared_ptr的實現了。
一般來說,智能指針的實現需要以下步驟:
1.一個模板指針T* ptr,指向實際的對象。
2.一個引用次數(必須new出來的,不然會多個shared_ptr里面會有不同的引用次數而導致多次delete)。
3.重載operator*和operator->,使得能像指針一樣使用shared_ptr。
4.重載copy constructor,使其引用次數加一。
5.重載operator=,如果原來的shared_ptr已經有對象,則讓其引用次數減一並判斷引用是否為零(是否調用delete)。
然后將新的對象引用次數加一。
6.重載析構函數,使引用次數減一並判斷引用是否為零(是否調用delete)。
源碼如下:
1 #ifndef __SHARED_PTR_ 2 #define __SHARED_PTR_ 3 4 template <typename T> 5 class shared_ptr { 6 public: 7 shared_ptr(T* p) : count(new int(1)), _ptr(p) {} 8 shared_ptr(shared_ptr<T>& other) : count(&(++*other.count)), _ptr(other._ptr) {} 9 T* operator->() { return _ptr; } 10 T& operator*() { return *_ptr; } 11 shared_ptr<T>& operator=(shared_ptr<T>& other) 12 { 13 ++*other.count; 14 if (this->_ptr && 0 == --*this->count) 15 { 16 delete count; 17 delete _ptr; 18 } 19 this->_ptr = other._ptr; 20 this->count = other.count; 21 return *this; 22 } 23 ~shared_ptr() 24 { 25 if (--*count == 0) 26 { 27 delete count; 28 delete _ptr; 29 } 30 } 31 int getRef() { return *count; } 32 private: 33 int* count; 34 T* _ptr; 35 }; 36 37 38 #endif