自己實現乙個智慧型指標

2021-10-11 19:16:34 字數 774 閱讀 1596

要實現乙個智慧型指標主要實現下面幾個函式

1 建構函式

2 拷貝建構函式

3 析構函式

4 賦值運算子函式

5 獲取引用計數函式

重點

1 構造,拷貝構造 +1

2 析構函式會使引用計數-1.

3 賦值運算子會使之前的引用計數-1。使新賦值過來的引用計數+1

#include

template

class smartptr

~smartptr()

}}smartptr

(const smartptr& s)

smartptr& operator=

(const smartptr& s)

}

ptr = s.ptr;

ref_count = s.ref_count;

(*ref_count)++;

return

*this;

} t* operator->()

smartptr& operator*()

intuse_count()

private:

t* ptr;

int*ref_count;};

intmain()

std:

:cout <<

"end"

<< std:

:endl;

return0;

}

智慧型指標初步認識 自己實現

目的 new出來的物件,需要程式設計師自己釋放堆上的空間,智慧型指標就是把堆上的空間同棧一起釋放 過載 讓智慧型指標像普通指標一樣使用 分析更簡單明瞭 include using namespace std class person void showage person private int m...

智慧型指標的乙個bug

先show乙個例項 class father father virtual void fun class mother mother virtual void test int a class son publicfather public mother son void fun int tmain...

編寫乙個智慧型指標類

比起一般指標,智慧型指標會自動地管理記憶體 釋放不需要的記憶體 而不需要程式設計師去操心。它能避免迷途指標 dangling pointers 記憶體洩漏 memory leaks 分配失敗等情況的發生。智慧型指標需要為所有例項維護乙個引用計數,這樣才能在恰當的時刻 引用計數為0時 將記憶體釋放。i...