面試時實現智慧指標shared_ptr
阿新 • • 發佈:2020-07-24
轉載:面試時實現智慧指標
#include<iostream> #include<cstdio> using namespace std; template<typename T> class SmartPointer { public: //建構函式 SmartPointer(T* ptr) { ref = ptr; ref_count = (unsigned int*)malloc(sizeof(unsigned)); *ref_count = 1; } //拷貝建構函式 SmartPointer(const SmartPointer<T>& other) { ref = other.ref; ref_count = other.ref_count; ++*ref_count;//引用計數增加 } //賦值運算子過載 SmartPointer& operator=(SmartPointer<T>& other) { if (this == &other) return *this; //引用計數為0時呼叫析構 if (--*ref_count == 0) { clear(); } ref = other.ref; ref_count = other.ref_count; ++*ref_count; return *this; } //取地址 T& operator*() { return *ref; } //取值 T* operator->() { return ref; } //解構函式 ~SmartPointer() { if (--*ref_count == 0) { clear(); } } private: //析構處理 void clear() { delete ref; free(ref_count); ref = NULL; ref_count = NULL; } protected: T* ref;//指標 unsigned int* ref_count;//引用計數 }; void main() { int* p = new int(); *p = 11; SmartPointer<int> ptr1(p); SmartPointer<int> ptr2 = ptr1; *ptr1 = 1; cout << *ptr1 << " " << *ptr2 << endl; }