C 智慧型指標總結

2021-07-10 17:26:53 字數 2362 閱讀 2944

智慧型指標raii:資源分配及初始化,定義乙個類來封裝資源的分配和初始化,在建構函式完成資源的分配和初始化,在析構函式完成資源的清理,可以保證資源的正確初始化和釋放

#pragma

once

//autoptr 智慧型指標

template

<

class

t>

class

autoptr

//拷貝構造

//把ap1股給ap2後,再把自己置為空,不再管理這個記憶體空間

autoptr(

autoptr

<

t>&ap)

:_ptr(

ap._ptr)

//賦值運算子過載

//釋放ap3,讓ap3指向ap2所指空間,再把ap2置空

autoptr

<

t>& operator=(

autoptr

<

t>&ap)

return

*this

; }

//析勾函式

~autoptr()

} //operator*

t& operator*()

//operator->

t* operator->()

//getptr

t* getptr()

protected:t

* _ptr;

};// 智慧型指標管理一塊記憶體的釋放

// 智慧型指標是乙個類,有類似指標的功能

struct

node ;

void

testautoptr()

//autoptr容易出錯,因為前面的指標已經置為空,存在潛在危險,沒有完全達到指標的效果,

//scopedptr 智慧型指標

template

<

class

t>

class

scopedptr

//析勾函式

~scopedptr()

} //過載*

t& operator*()

//operator->

t* operator->()

//getptr

t* getptr()

protected

://1.限定符為protected,不能進行拷貝,2.將拷貝構造和賦值運算子的過載宣告出來

//不能讓他呼叫預設的,也不能在外面定義它

scopedptr(

const

scopedptr

<

t>& sp);

scopedptr

<

t> operator=(

const

scopedptr

<

t>& sp);

protected:t

* _ptr;

};//防止別人在類外面定義它

//template

//scopedptr::scopedptr(const scopedptr& sp)

//       :_ptr(sp._ptr)

//{}

void

testscopedptr()

//sharedptr 利用引用計數來解決這個問題

template

<

class

t>

class

sharedptr

~sharedptr()

//只是改變pcount

sharedptr(

const

sharedptr

<

t>&sp)

:_ptr(

sp._ptr)

, _pcount(

sp._pcount)

賦值運算子的傳統寫法

//sharedptr& operator=(const sharedptr& sp)

////       return *this;

//}//現**法

sharedptr

<

t>& operator=(

sharedptr

<

t>sp)

t& operator*()

t* operator->()

t* getptr()

long

getcount()

protected

:void

_release()

} protected:t

* _ptr;

long

* _pcount;

};void

testsharedptr()

智慧型指標總結

1.智慧型指標的原理 1 智慧型指標不是通常意義下的指標,而是乙個模板類,在對模板類例項化之後會產生類似於指標的行為。通過物件來管理資源。2 智慧型指標採用一種raii 資源分配即初始化 機制,在建構函式中實現對資源的分配及初始化,在析構函式中實現對資源的析構及 2.智慧型指標的分類 c 中最開始是...

智慧型指標總結

std shared ptr include class test public std enable shared from this void print intid int main std enable shared from this是乙個模板類,其中有乙個成員函式 shared ptrs...

智慧型指標總結

unique ptr weak ptr 智慧型指標與常規指標的區別 智慧型指標的選擇 智慧型指標並非c 11的原創,boost庫很早就提供了share ptr和weak ptr,c 11在此基礎上增加了unique ptr,從而形成了我們現在所說的智慧型指標。智慧型指標主要用於管理動態記憶體,當智慧...