C 智慧型指標的設計和實現

2021-06-20 18:41:17 字數 1985 閱讀 4070

在c++語言程式設計時,當類中有指標成員時,一般有兩種方式來管理指標成員:一是採用值型的方式管理,每個類物件都保留乙份指標指向的物件的拷貝;另一種更優雅的方式是使用

智慧型指標,從而實現指標指向的物件的共享。

智慧型指標(smart pointer)的一種通用實現技術是使用引用計數(reference count)。智慧型指標類將乙個計數器與類指向的物件相關聯,引用計數跟蹤該類有多少個物件共享同一指標。

每次建立類的新物件時,初始化指標並將引用計數置為1;當物件作為另一物件的副本而建立時,拷貝建構函式拷貝指標並增加與之相應的引用計數;對乙個物件進行賦值時,賦值操作符減少左運算元所指物件的引用計數(如果引用計數為減至0,則刪除物件),並增加右運算元所指物件的引用計數;呼叫析構函式時,析構函式減少引用計數(如果引用計數減至0,則刪除基礎物件)。

智慧型指標通常使用類模板來實現。模擬類指標的各種行為。但是,其最重要的作用是對類指標成員的管理,防止懸垂指標的出現。

template  

class

smartpointer

t& operator *()

t* operator ->()

private

: t *pt;

};

為了實現引用計數,我們定義乙個_counter類來記錄引用次數,把_counter類的所有成員設定為private,因為其他的型別並不需要訪問_counter,只有smartpointer對其進行操作就行了,smartpointer將設為其友元類。

class

_counter

~_counter(){}

intuse;

};

在smartpointer類中,保留_counter的指標。

template  

class

smartpointer

smartpointer(smartpointer

&rhs)

~smartpointer()

} smartpointer

& operator=(smartpointerrhs)

this->pt =rhs.pt;

this->pc =rhs.pc;

this->pc->use++;

cout

<

smartpointer::operator=() invoked use is:

"return *this

; }

private

: t *pt;

_counter*pc;

};

例如:我們有乙個hasptr類,其類成員中有乙個為指標*p。

class

hasptr

~hasptr()

private

:

int *p;

intvalue;

};

如果如下呼叫:

hasptr *php = new hasptr(3

);

smartpointer

psp(php);

smartpointer

npsp(psp);

我們現在有兩個智慧型指標物件,指向同乙個hasptr物件,其模型如下:

_counter的use成員(引用計數)為2.

int main(void

)

使用gcc編譯器,執行結果如下:

c 智慧型指標 C 智慧型指標是如何實現的

c 程式執行時,計算機記憶體從大類上分為棧和堆,在棧上的記憶體是由系統自動分配和 的,而堆上的記憶體卻是由程式設計師手動申請和釋放的,如果程式設計師在記憶體的管理上出現失誤,輕則程式執行結果與預期有差距,重則程式直接崩潰 棧和堆記憶體 區別 棧記憶體上的變數在過了作用域 大括號 後系統會自動 而堆記...

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...