智能指针主要是做了两件事情:
- 申请内存,我们用模板指针 T* ptr
- 另一个进行计数并销毁清理对象
注意多个智能指针里的ptr可能会指向同一快内存,所以计数的变量也是要同步的,在这里我们用一个指针int* count来计数,每次新建一个共享指针就对count进行浅拷贝,这样多个指针指针就能同步进行更新计数了
当我们重载operator=的时候,要注意如果原来的共享指针已经有对象,需要将原来的引用计数减一并判断是否需要释放内存
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 82
| #include<iostream> #include <memory> using namespace std; template<class T> class S_ptr { public: S_ptr(); S_ptr(T *p); ~S_ptr(); S_ptr(const S_ptr<T> &org); S_ptr<T>& operator = (const S_ptr<T> &org); int get_count(); void get(); private: int *use_count; T *ptr; };
template<class T> S_ptr<T>::S_ptr() : ptr(), use_count(new int (1)) { cout << "Allocation11" << endl; }; template<class T> S_ptr<T>::S_ptr(T *p) : ptr(p) { use_count = new int(1); cout << "Allocation22" << endl; if (use_count == nullptr) { p = nullptr; cout << "Allocation Error" << endl; return; } }
template<class T> S_ptr<T>::~S_ptr() { if (--*use_count == 0) { delete ptr; ptr = nullptr; delete use_count; use_count = nullptr; } }
template<class T> S_ptr<T>::S_ptr(const S_ptr<T> &org) { ptr = org.ptr; use_count = org.use_count; (*use_count)++; } template<class T> S_ptr<T>& S_ptr<T>::operator = (const S_ptr &org) { if (this->ptr) { if (--this->use_count == 0) { delete this->ptr; delete this->count; } this->ptr = org.ptr; this->use_count = org.use_count; (*use_count)++; } return *this; } template<class T> S_ptr<T>::get_count() { return *use_count; }
int main() { S_ptr<string> p1(new string("hello")); shared_ptr<int> p(new int(2)); cout << p1.get_count() << endl; S_ptr<string> p2(p1); cout << p1.get_count() << endl; { S_ptr<string> p3(p1); cout << p1.get_count() << endl; } cout << p1.get_count() << endl; return 0; }
|