C 實現智慧型指標

2021-09-24 21:55:53 字數 1690 閱讀 1242

c++11增加了智慧型指標:shared_ptr、unique_ptr、weak_ptr

為了加深理解,自己實現智慧型指標

我們都知道shared_ptr的核心思想通過引用計數來管理記憶體

先實現單個指標的自我管理,看下面

template class ref

ref(t* p) : m_ptr(p)

ref(const ref& r) : m_ptr(r.m_ptr)

template ref(const ref& r) : m_ptr(r.get())

~ref()

t* get() const

operator t*() const

t* operator->() const

t* release()

ref& operator=(t* p)

ref& operator=(const ref& r)

template ref& operator=(const ref& r)

void swap(t** pp)

void swap(ref& r)

protected:

t* m_ptr;

};

這部分不難理解

那麼,再來需要管理的類的基類

//智慧型指標基類所有智慧型指標物件都繼承該類

class refcountedbase

};

而我們自定義的類需要繼承自此類,但是需要實現addref和release,為了方便,再定義乙個模板類用於管理計數

template class refcountedobject : public t 

templateexplicit refcountedobject(p p) : t(p), m_count(0)

templaterefcountedobject(p1 p1, p2 p2) : t(p1, p2), m_count(0)

templaterefcountedobject(p1 p1, p2 p2, p3 p3) : t(p1, p2, p3), m_count(0)

templaterefcountedobject(p1 p1, p2 p2, p3 p3, p4 p4)

: t(p1, p2, p3, p4), m_count(0)

templaterefcountedobject(p1 p1, p2 p2, p3 p3, p4 p4, p5 p5)

: t(p1, p2, p3, p4, p5), m_count(0)

virtual int addref()

virtual int release()

return count;

}protected:

virtual ~refcountedobject()

std::atomic_int m_count;

};

而我門在使用的時候,只需類似 shared_ptr的用法:

std::shared_ptr= std::make_shared(); 

class test:public refcountedbase

};reftest=new refcountedobject()

test->test();

參考:

C 智慧型指標實現

1 問題的提出 先看下面的例子 class ctext ctext private int m ptr int funtext 在函式funtext 中,類的兩個物件共用了new出來的指標ptr。當函式執行開始時,呼叫兩次建構函式 退出執行時,呼叫兩次析構函式,而在第一次呼叫時已經delete pt...

智慧型指標實現C

include using namespace std template class shared ptrelse shared ptr const shared ptr ptr shared ptr operator const shared ptr ptr if this ptr this pt...

C 實現智慧型指標

include include using namespace std 智慧型指標自我實現 template typename t class myautoptr myautoptr const myautoptr ptr myautoptr operator const myautoptr ptr...