1. 程式人生 > 其它 >智慧指標 shared_ptr 簡易實現

智慧指標 shared_ptr 簡易實現

template <typename T>
class shared_ptr {
private:
    int* count; // 引用計數,不同shared_ptr指向同一引用計數
    T* ptr; // 模板指標ptr,不同shared_ptr指向同一物件

public: 
    // 建構函式
    shared_ptr(T* p) : count(new int(1)), ptr(p) {}

    // 複製建構函式,引用計數+1
    shared_ptr(shared_ptr<T>& other) : count(&(++* other.count)), ptr(other.ptr) {}

    T
* operator->() return ptr; T& operator*() return *ptr; // 賦值操作符過載 shared_ptr<T>& operator=(shared_ptr<T>& other) { ++* other.count; // 如果原shared_ptr已經指向物件 // 將原shared_ptr的引用計數-1,並判斷是否需要delete if (this->ptr && -- *this->count==0
) { delete count; delete ptr; } // 更新原shared_ptr this->ptr = other.ptr; this->count = other.count; return *this; } // 解構函式 ~shared_ptr() { // 引用計數-1,並判斷是否需要delete if (-- * count == 0) { delete count;
delete ptr; } } // 獲取引用計數 int getRef() return *count; };