C 自學筆記 詳細理解智慧型指標

2021-09-26 07:35:26 字數 3393 閱讀 8080

raii是一種利用物件生命週期來控制程式資源(記憶體、檔案控制代碼、網路連線、互斥量等等)的簡單技術;

在物件構造時獲取資源,接著控制對資源的訪問使之在物件的生命週期內始終有效,最後在物件析構的時候釋放資源。藉此,我們實際上把管理乙份資源的責任託管給了乙個物件,有兩大好處:

c++98版本庫中提供的auto_ptr的智慧型指標;

class date 

~date()

int _year;

int _mouth;

int _day;

};void test()

auto_ptr的實現原理:管理許可權轉移,下面簡化模擬實現了乙份 autoptr 來了解它的原理;

templateclass autoptr 

~autoptr()

} autoptr(autoptr& ap)

:_ptr(ap._ptr)

autoptroperator=(autoptr& ap)

_ptr = ap._ptr;

ap._ptr = null;

} return *this;

} t& operator*()

t* operator->()

private:

t* _ptr;

};

一旦發生拷貝,就將 ap 中的資源轉移到當前物件中,然後另 ap 與其所管理的資源斷開聯絡;

unique_ptr的實現原理:簡單粗暴的防拷貝!!

templateclass uniqueptr 

~uniqueptr()

} t& operator*()

t* operator->()

private:

//c++98,只(私有)宣告不實現

uniqueptr(uniqueptrconst&);

uniqueptr& operator=(uniqueptrconst&);

//c++11,防拷貝 delete

uniqueptr(uniqueptrconst&) = delete;

uniqueptr& operator=(uniqueptrconst&) = delete;

private:

t* _ptr;

};

c++11推出的更靠譜且支援拷貝的智慧型指標;

1、shared_ptr的原理:是通過引用計數的方式來實現多個 shared_ptr 物件之間共享資源;

templateclass sharedptr 

~sharedptr()

sharedptr(const sharedptr& sp)

:_ptr(sp._ptr)

,_prefcount(sp._prefcount)

,_pmutex(sp._pmutex)

sharedptr& operator=(const sharedptr& sp)

return *this;

} t& operator*()

t* operator->()

int usecount()

t* get()

void addrefcount()

private:

void release()

_pmutex->unlock();

if (deleteflag == true)

}private:

t* _ptr;

int* _prefcount; //引用計數

mutex* _pmutex; //互斥鎖

};

引入一段測試函式,試一試:

大致的執行過程如下所示:申請了一塊資源 a,由 sp1 指向該資源,此時 a 資源的引用計數是1;拷貝構造了sp2,也是指向資源 a,所以此時的引用計數需要加1,此時 a 資源的引用計數是2;申請了另一塊資源b,由sp3指向該資源,此時 b 資源的引用計數是1;執行 sp2 = sp3,此時sp2 和 sp3 指標都指向 b資源,所以此時的引用計數是2,而a資源,現在只有sp1,所以計數為1;執行 sp1 = sp3,此時 sp1 、 sp2 、sp3都指向b資源,所以此時的引用計數是3;

2、std::shared_ptr的執行緒安全問題:

3、std::shared_ptr的迴圈引用:

node1和node2兩個智慧型指標物件指向兩個節點,引用計數變為1,不需要手動delete;

node1的_next 指向 node2,node2 的_prev指向 node1,引用計數變成2;

_next 屬於node 的成員,node1 釋放了,_next才會析構,而node1 由_prev管理,_prev 屬於 node2成員,構成迴圈引用,誰也不會釋放;

為了解決迴圈引用問題,引入了 weak_ptr

weak_ptr的作用就是:node1->_next = node2;和 node2->_prev = node1 時 weak_ptr 的 next 和prev 不會增加node1 和node2的引用計數;4、對於不是new 出來的物件(刪除器)

c 智慧型指標的理解

智慧型指標的運用是c 裡很重要的乙個方面。智慧型指標是為了更容易的動態的管理和使用動態記憶體而設計的,新的標準庫提供兩種智慧型指標。乙個是shared ptr 允許多個指標指向同乙個物件 乙個是unique ptr 獨佔所指向的物件。還有一種伴隨類 weak ptr 他是一種弱引用 指向shared...

智慧型指標筆記

前言智慧型指標是行為類似於指標的類物件。include include using namespace std void fun string str int main system pause return0 void fun string str 可以看出此 中有缺陷,在fun函式中,分配了堆中...

c 智慧型指標複習筆記

shared ptr 變數出了作用域之後智慧型指標會析構,引用計數 1,直到為0時銷毀物件,呼叫物件的析構函式,哪怕是出現了異常。weak ptr解決迴圈引用問題 unique ptr它不允許其他的智慧型指標共享其內部的指標,不允許通過賦值將乙個unique ptr賦值給另乙個unique ptr ...