先來說一下四種常用的智慧型指標,我按使用度從低到高排一下順序,分別是auto_ptr, unique_ptr, shared_ptr, weak_ptr,先來列舉一下啊,剩下的我在乙個乙個慢慢說呀
首先來說一下智慧型指標的實現原理主要是通過物件生命週期來控制程式資源的簡單技術,然後了既然是指標就是可以進行和指標類似的行為(解引用和空間內容的訪問)
templateclass autoptr
// 拷貝構造:將ap的資源轉移到當前物件上
autoptr(autoptr& ap)
: _ptr(ap._ptr)
autoptr& operator=(autoptr& ap)
return *this;
} ~autoptr() }
t& operator*()
t* operator->()
t* get()
void reset(t* ptr)
protected:
t* _ptr;
};struct a
;void testautoptr1()
最顯著的特點就是乙個物件的空間只能乙個物件用,不可以兩個物件共用同一塊空間,避免了程式崩潰問題,當我們賦值以後我們以前的物件資源就被置空了。
我們使用智慧型指標的時候我們必須加#include,然後了賦值以後我們以前的物件空間就不能訪問了哦。
class date
~date()
int _year;
int _month;
int _day;
};int main()
#includeusing namespace std;
templateclass uniqueptr
~uniqueptr() }
t& operator*()
t* operator->()
t* get()
private:
uniqueptr(const uniqueptr&);
uniqueptr& operator=(const uniqueptr&);
protected:
t* _ptr;
};void testuniqueptr()
int main()
如果我們試圖對unique_ptr進行賦值拷貝時候,就會出現程式崩潰。
unique_ptr的簡單的使用
unique_ptrup1(new int);
unique_ptrup2(new int);
先來簡單的說一下shared_ptr吧,上面兩個指標也許相比shared_ptr使用度並不是很高,相比之下最簡單的話說shared_ptr是更加智慧型的智慧型指標,shared_ptr是通過引用計數的方法管理同一塊記憶體的,這樣記憶體什麼時候釋放,記憶體指向會不會成為野指標就知道了。
templateclass sharedptr
} ~sharedptr() }
sharedptr(const sharedptr& sp)
: _ptr(sp._ptr)
, _pcount(sp._pcount)
sharedptr& operator=(const sharedptr& sp)
_ptr = sp._ptr;
_pcount = sp._pcount;
if (sp._ptr)
++(*_pcount);
} return *this;
} int usecount()
t& operator*()
t* operator->()
protected:
t* _ptr;
int* _pcount;
};void testsharedptr1()
void testsharedptr2()
int main()
#include template>
class sharedptr
} ~sharedptr()
sharedptr(const sharedptr& sp)
: _ptr(sp._ptr)
, _pcount(sp._pcount)
, _pmutex(sp._pmutex)
// s1、s2
// s1 = s2;
sharedptr& operator=(const sharedptr& sp)
return *this;
} int usecount()
t& operator*()
t* operator->()
void increaserefcount()
int decreaserefcount()
void release() }
protected:
t* _ptr;
int* _pcount;
mutex* _pmutex;
};class date
;void testsharedthread(sharedptr& sp, int n)
}
但是在特定環境當中shared_ptr的引用計數未必也是湊效的,例如雙向鍊錶的迴圈引用,這個時候我們必須在雙向節點內部在新增乙個引用計數的指標用來通知釋放內部節點,就需要乙個weak_ptr![](https://pic.w3help.cc/e4f/6976f323553eb81107525512aed2a.jpeg)
struct listnode
};int main()
四種智慧型指標剖析
個人部落格傳送門 智慧型指標是c 中乙個程式設計技巧。它保證記憶體的正確釋放,解決了記憶體洩漏的問題。有乙個思想叫做raii,raii指的是資源分配即初始化。我們通常會定義乙個類來封裝資源的分配和釋放,在建構函式中完成資源的分配和初始化,在析構函式中完成資源的清理。在c 中,我們一般是使用new和d...
stl的四種智慧型指標
第一種 std auto ptr auto ptr是所有權轉移的智慧型指標,也就是同一時刻只有乙個智慧型指標物件對原物件擁有所有權。第二種 std scoped ptr scoped ptr智慧型指標無法使用乙個物件建立另乙個物件,也無法採用賦值的形式。這無疑提公升了智慧型指標的安全性,但是又存在無...
C 四種智慧型指標詳解
c 裡面的四個智慧型指標 shared ptr,unique ptr,weak ptr,auto ptr其中前三個是c 11支援,並且最後乙個已經被11棄用。智慧型指標的使用 智慧型指標主要用於管理在堆上分配的記憶體,它將普通的指標封裝為乙個棧物件。當棧物件的生存週期結束後,會在析構函式中釋放掉申請...