C++——智能指针
C++的內(nèi)存管理是一個(gè)很大的問題,C++程序員總是會(huì)無意間的造成內(nèi)存泄漏的問題,C++98給出了智能指針的解決方案,智能指針會(huì)在銷毀指針的時(shí)候自動(dòng)銷毀指針指向的內(nèi)容(例如棧解退)。
智能指針是一個(gè)模板類,可以看成一個(gè)被包裝過的指針。他的構(gòu)造函數(shù)如下
template <class X> class auto_ptr { public:explicit auto_ptr(X * p=0) throw() {} };他將獲得一個(gè)指向X的指針。
使用智能指針后的程序
#include <iostream> #include <string> #include <memory> using namespace std;int main() {auto_ptr<string> ps(new string ("hello"));//don't need deletecout << *ps;return 0; }運(yùn)行結(jié)果
在只能指針ps被銷毀的時(shí)候,會(huì)調(diào)用其析構(gòu)函數(shù)釋放ps指向的內(nèi)容。
我們也可以寫一個(gè)自己的簡單的智能指針
include <iostream> #include <string> #include <memory> using namespace std; template <class T> class my_auto_ptr { private:T * ptr; public:explicit my_auto_ptr(T * p= nullptr) : ptr(p) {}~my_auto_ptr(){delete ptr;}T & operator*(){return *ptr;} }; int main() {my_auto_ptr<string> ps (new string("hello"));cout << *ps;return 0; }想進(jìn)一步包裝的話還可以重載-> =等運(yùn)算符。
這種智能指針(auto_ptr)在進(jìn)行賦值運(yùn)算時(shí)可能會(huì)有問題,又或者是不經(jīng)意間重復(fù)釋放內(nèi)存,有以下幾種解決方案
1.重載=進(jìn)行深拷貝
2.建立所有權(quán)的概念,每個(gè)對象只有一個(gè)智能指針擁有它,=是所有權(quán)的轉(zhuǎn)讓
unique_ptr
3.創(chuàng)建智能性更高的指針,記錄構(gòu)造函數(shù)和析構(gòu)函數(shù)的次數(shù),判斷是否釋放。
shared_ptr
?unique_ptr的使用比較嚴(yán)格
編譯器不允許將將這類對象賦值給另一個(gè)對象,但如果對象是一個(gè)臨時(shí)的右值則可以(如返回值)。
int main() {unique_ptr<string> ps;unique_ptr<string> pd;pd = ps; //errorreturn 0; }?這樣可以,這將"hello"的所有權(quán)從temp變成了主函數(shù)中的ps
unique_ptr<string> t(const char * s) {unique_ptr<string> temp(new string(s));return temp; } int main() {unique_ptr<string> ps;ps = t("hello");cout << *ps;return 0; }注意:智能指針的本質(zhì)也是使用new和delete,其中,只有unique_ptr有[]delete的版本,不要讓只能指針指向非new出來的對象。
?在unique_ptr為右值時(shí),可將其賦值給shared_ptr,因?yàn)楹笳呤怯?jì)數(shù)處理。
shared_ptr有一個(gè)構(gòu)造函數(shù),可將右值unique_prt轉(zhuǎn)換為shared_prt,shared_ptr將接管原來unique_prt接管的對象。
智能指針的選擇
如果要將多個(gè)指針指向同一個(gè)對象,應(yīng)選擇shared_ptr
SLT很多算法都支持賦值和賦值操作,可用于shared_prt
不需要用多個(gè)指針指向同一個(gè)對象,?可使用unique_ptr
用new分配的內(nèi)存,并返回該內(nèi)存的指針,unique_prt是個(gè)不錯(cuò)的選擇
總結(jié)
- 上一篇: pxcook
- 下一篇: 【c++复习笔记】——智能指针详细解析(