智慧型指標 weak ptr的用法和實現

2021-10-14 08:25:30 字數 1793 閱讀 2169

如果std::shared_ptr仔細考慮,您仍然會發現仍然存在無法釋放資源的問題。看下面的例子

#include

//記憶體洩露檢測工具

#include

#include

classa;

classb;

classa}

;classb}

;int

main()

memory not freed:

address size caller

0x0000000000b84370 0x20 at 0x7f6e26ecee78

0x0000000000b843a0 0x20 at 0x7f6e26ecee78

原因:這兩塊記憶體均由a(b)指標和b(a)的成員指標所指向,a和b析構後,堆上成員指標和記憶體依然相互依存,造成記憶體洩露。

解決方法:使用弱引用weak_ptr,弱引用不會引起計數器計數。

**如下(示例):

#include

using

namespace std;

template

<

typename t>

class

weak_ptr

;class

count;~

count()

;};template

<

typename t>

class

smartptr

~smartptr()

//smartptr拷貝建構函式 count.s++

smartptr

(const smartptr

& orig)

:ptr_

(orig.ptr_)

,cnt_

(orig.cnt_)

smartptr

operator=(

const smartptr

& orig)

return orig;

}int

use_count()

t*operator

->()

t&operator*(

) t*

get(

)friend

class

weak_ptr

;private

: t* ptr_;

//堆上方便共享

count* cnt_;

void

del()}

}};template

<

typename t>

class

weak_ptr

weak_ptr

(weak_ptr

& s)

:ptr_

(s.ptr_)

,cnt_

(s.cnt_)

weak_ptr

&operator

=(smartptr

& s)

return

*this;}

weak_ptr

&operator

=(weak_ptr

& w)

return w;}~

weak_ptr()

private

: t* ptr_;

count* cnt_;

void

del()}

};intmain()

智慧型指標weak ptr

智慧型指標weak ptr主要用來協助shared ptr。不參與引用計數,但是有以下好處 1 打破遞迴的依賴關係 2 使用乙個共享的資源但是不要所有權,不新增引用計數 3 避免懸空指標。使用方法有二 方法一 boost shared ptrsp new std string method1 從sh...

智慧型指標 weak ptr

weak ptr是為了配合shared ptr而引入的一種智慧型指標,它更像是shared ptr的乙個助手而不是智慧型指標,因為它不具有普通指標的行為,沒有過載operator 和 它的最大作用在於協助shared ptr工作,像旁觀者那樣觀測資源的使用情況.用法 weak ptr被設計為與sha...

智慧型指標 weak ptr

weak ptr weak ptr是為了配合shared ptr而引入的一種智慧型指標,它更像是shared ptr的乙個助手而不是智慧型指標,因為它不具有普通指標的行為,沒有過載operator 和 它的最大作用在於協助shared ptr工作,像旁觀者那樣觀測資源的使用情況.用法 weak pt...