模擬實現boost庫里的智慧型指標

2021-08-03 16:29:27 字數 2155 閱讀 1340

#include

#include

using

namespace

std;

//模擬實現auto_ptr,非常坑爹什麼情況下都不要使用

template

class auto_ptr

auto_ptr(auto_ptr &a)//拷貝建構函式

auto_ptr & operator=(auto_ptr& a)

_ptr = a._ptr;

a._ptr = null;

}return *this;

}~auto_ptr()

}private:

t *_ptr;

};

第二種實現方法-新增bool變數

template

class auto_ptr

}auto_ptr(auto_ptr &a)//拷貝建構函式

auto_ptr & operator=(auto_ptr& a)

_ptr = a._ptr;

a.onlyone = false;

onlyone = true;

}return *this;

}~auto_ptr()

}private:

t *_ptr;

bool onlyone;

};

兩種方法各有優缺點,這裡我們來看一下第二種的bug.

void funtest()

//出了if作用域空間就會被釋放,此時使用ap1指標就會出現問題

}

#define  _crt_secure_no_warnings 1

#include

#include

using

namespace

std;

template

class scopedptr

~scopedptr()

}private:

//為了防止淺拷貝的問題出現,使這個類無法被拷貝和賦值

//採用的方法就是將拷貝建構函式和賦值運算子過載函式

//訪問許可權設為私有,並且只給出宣告。

scopedptr(const scopedptr& s);

t &operator=(const scopedptr& s);

private:

t *_p;

};void funtest()

int main()

乙個類如何防拷貝呢?

1.宣告為私有的:這樣可以通過友元函式和成員函式拷貝成成功(不可取)

2.宣告為公有:可能在類外被定義(不可取)

3.宣告為私有(只給出宣告)(可以實現)

最後我們來模擬boost庫中shared_ptr,但這個函式執行緒不是很安全,一般建議使用scoped_ptr

#define  _crt_secure_no_warnings 1

#include

#include

using

namespace

std;

//共享的智慧型指標

//使用引用計數

template

struct delete

}};struct fclose

}};template

class sharedptr

}sharedptr(const sharedptr& sp)//拷貝建構函式

:_p(sp._p)

,_pcount(sp._pcount)

}sharedptr& operator=(const sharedptr& sp)

}_p = sp._p;//和其他物件共同管理

_pcount = sp._pcount;

if(null != sp._pcount)//注意判斷賦值物件是否為空

}return *this;

}~sharedptr()

private:

void release()

}private:

t *_p;

int *_pcount;

_del _del;

};

模擬實現Boost庫中的智慧型指標 上

智慧型指標 英語 smart pointer 是一種抽象的資料型別。在程式設計中,它通常是經由類模板 class template 來實做,藉由模板 template 來達成泛型,通常藉由類 class 的析構函式來達成自動釋放指標所指向的儲存器或物件。起初在c 標準庫裡面是沒有智慧型指標的,直到c...

模擬實現智慧型指標

智慧型指標可以用來管理資源,原自構造析構函式 raii 還可以像原生指標一樣使用。auto ptr 管理許可權的轉移。scoped ptr 防拷貝。shared ptr 引用計數解決auto ptr的缺陷。其中shared 自身帶有一定缺陷,迴圈引用,和不可釋放陣列類,檔案類等資源,幸運的是它支援定...

智慧型指標的模擬實現

1.引入 int main 在上面的 中定義了乙個裸指標p,需要我們手動釋放。如果我們一不小心忘記釋放這個指標或者在釋放這個指標之前,發生一些異常,會造成嚴重的後果 記憶體洩露 而智慧型指標也致力於解決這種問題,使程式設計師專注於指標的使用而把記憶體管理交給智慧型指標。普通指標也容易出現指標懸掛問題...