C 實現智慧型指標 三

2021-08-19 17:08:06 字數 2425 閱讀 2304

一. 實現版本v3

每乙個物件負責維護物件所有引用的計數值。當乙個新的引用指向物件時,引用計數器就遞增,當去掉乙個引用時,引用計數就遞減。當引用計數到零時,該物件就將釋放占有的資源。

引用計數需要儲存在被引用的資源物件裡,乙個資源物件對應乙個引用計數, 當其引用計數為0時,資源物件可以被銷毀。

需要修改以下函式中實現計數功能:

接收不同物件型別的建構函式:這個建構函式實現,比較簡單,直接將引用計數加1 即可

析構函式:析構函式的實現,不能再直接做delete操作,而是需要先對引用計數減1,當引用計數為0時,才做delete操作。

拷貝建構函式:拷貝建構函式的實現,底層指標共享,然後將引用計數加1 即可。

賦值操作符:賦值操作的實現,稍微複雜一些,涉及到將新指向物件的引用計數加1,將原指向物件的引用計數減1,如果有需要還要銷毀原指向物件。這裡有一點值得注意的地方,我們新的賦值操作的實現,不再需要if (this == &other) return *this;語句處理自我賦值的情況,讀者可自行分析一下我們新的賦值操作的實現為何不需要通過if語句去處理自我賦值的情況。

為了能夠使用引用計數技術,我們的智慧型指標不能再像原生指標那樣能用可以指向任意資源物件,我們的智慧型指標只能指向實現了存在方法increfcount和方法decrefcount的資源類了。

/* 

* file name : smartpointer.h

* desp : 智慧型指標版本v3

*/#ifndef __smartpointer_h__

#define __smartpointer_h__

template // 將智慧型指標類定義成模板類

class smartpointer

// 接收不同物件型別的建構函式

smartpointer(t *p):mpointer(p)

// 析構函式

~smartpointer()

// 拷貝建構函式

smartpointer(const smartpointer &other):mpointer(other.mpointer)

// 賦值操作符

smartpointer &operator = (const smartpointer &other)

private:

t *mpointer; // 指向智慧型指標實際對應的記憶體資源,根據引數自動推導規則,定義內部資源指標型別

};/*引用計數基類*/

class refbase

void increfcount()

int decrefcount()

// 除錯介面,返回物件當前引用計數

int getrefcount()

virtual ~refbase()

private:

int mcount;

};

#endif // __smartpointer_h__

/* 

* file name : sptestcase3.cpp

* desp : 智慧型指標測試** case3 測試智慧型指標的引用計數功能

*/#include #include "smartpointer.h"

/*繼承於引用計數基類的someclass類*/

class someclass: public refbase

std::cout << "someclass ref count (" << psomeclass->getrefcount() << ") outer 2."<< std::endl;

// delete psomeclass ; 不需要也不能執行delete操作!

std::cout << "new another someclass class for spouter."<< std::endl;

smartpointerspouter2 = new someclass();

spouter = spouter2;// 1處new出來的someclass將會被自動釋放

}int main(void)

結果分析

二. 知識點查漏補缺

假設我們有多個智慧型指標指向一塊記憶體資源,當其中某個指標被銷毀了之後,就會自動去釋放其所指向的記憶體資源,這最終會導致,其他還在使用中並且引用了改記憶體資源的智慧型指標,則smartpointer2為野指標。故採用引用計數技術。

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 實現智慧型指標

c 11增加了智慧型指標 shared ptr unique ptr weak ptr 為了加深理解,自己實現智慧型指標 我們都知道shared ptr的核心思想通過引用計數來管理記憶體 先實現單個指標的自我管理,看下面 template class ref ref t p m ptr p ref ...