详解C++11智能指针
詳解C++11智能指針
前言
C++里面的四個智能指針: auto_ptr, unique_ptr,shared_ptr, weak_ptr 其中后三個是C++11支持,并且第一個已經(jīng)被C++11棄用。
C++11智能指針介紹
智能指針主要用于管理在堆上分配的內(nèi)存,它將普通的指針封裝為一個棧對象。當棧對象的生存周期結(jié)束后,會在析構(gòu)函數(shù)中釋放掉申請的內(nèi)存,從而防止內(nèi)存泄漏。C++ 11中最常用的智能指針類型為shared_ptr,它采用引用計數(shù)的方法,記錄當前內(nèi)存資源被多少個智能指針引用。該引用計數(shù)的內(nèi)存在堆上分配。當新增一個時引用計數(shù)加1,當過期時引用計數(shù)減一。只有引用計數(shù)為0時,智能指針才會自動釋放引用的內(nèi)存資源。對shared_ptr進行初始化時不能將一個普通指針直接賦值給智能指針,因為一個是指針,一個是類。可以通過make_shared函數(shù)或者通過構(gòu)造函數(shù)傳入普通指針。并可以通過get函數(shù)獲得普通指針。
為什么要使用智能指針
智能指針的作用是管理一個指針,因為存在以下這種情況:申請的空間在函數(shù)結(jié)束時忘記釋放,造成內(nèi)存泄漏。使用智能指針可以很大程度上的避免這個問題,因為智能指針就是一個類,當超出了類的作用域是,類會自動調(diào)用析構(gòu)函數(shù),析構(gòu)函數(shù)會自動釋放資源。所以智能指針的作用原理就是在函數(shù)結(jié)束時自動釋放內(nèi)存空間,不需要手動釋放內(nèi)存空間。
auto_ptr
(C++98的方案,C++11已經(jīng)拋棄)采用所有權(quán)模式。
auto_ptr<string> p1 (new string ("I reigned lonely as a cloud.")); auto_ptr<string> p2; p2 = p1; //auto_ptr不會報錯.此時不會報錯,p2剝奪了p1的所有權(quán),但是當程序運行時訪問p1將會報錯。所以auto_ptr的缺點是:存在潛在的內(nèi)存崩潰問題!
unique_ptr
(替換auto_ptr)unique_ptr實現(xiàn)獨占式擁有或嚴格擁有概念,保證同一時間內(nèi)只有一個智能指針可以指向該對象。它對于避免資源泄露(例如“以new創(chuàng)建對象后因為發(fā)生異常而忘記調(diào)用delete”)特別有用。
采用所有權(quán)模式,還是上面那個例子
unique_ptr<string> p3 (new string ("auto")); //#4 unique_ptr<string> p4; //#5 p4 = p3;//此時會報錯!!編譯器認為p4=p3非法,避免了p3不再指向有效數(shù)據(jù)的問題。嘗試復(fù)制p3時會編譯期出錯,而auto_ptr能通過編譯期從而在運行期埋下出錯的隱患。因此,unique_ptr比auto_ptr更安全。
另外unique_ptr還有更聰明的地方:當程序試圖將一個 unique_ptr 賦值給另一個時,如果源 unique_ptr 是個臨時右值,編譯器允許這么做;如果源 unique_ptr 將存在一段時間,編譯器將禁止這么做,比如:
unique_ptr<string> pu1(new string ("hello world")); unique_ptr<string> pu2; pu2 = pu1; // #1 不允許 unique_ptr<string> pu3; pu3 = unique_ptr<string>(new string ("You")); // #2 允許其中#1留下懸掛的unique_ptr(pu1),這可能導(dǎo)致危害。而#2不會留下懸掛的unique_ptr,因為它調(diào)用 unique_ptr 的構(gòu)造函數(shù),該構(gòu)造函數(shù)創(chuàng)建的臨時對象在其所有權(quán)讓給 pu3 后就會被銷毀。這種隨情況而已的行為表明,unique_ptr 優(yōu)于允許兩種賦值的auto_ptr 。
注:如果確實想執(zhí)行類似與#1的操作,要安全的重用這種指針,可給它賦新值。C++有一個標準庫函數(shù)std::move(),讓你能夠?qū)⒁粋€unique_ptr賦給另一個。盡管轉(zhuǎn)移所有權(quán)后 還是有可能出現(xiàn)原有指針調(diào)用(調(diào)用就崩潰)的情況。但是這個語法能強調(diào)你是在轉(zhuǎn)移所有權(quán),讓你清晰的知道自己在做什么,從而不亂調(diào)用原有指針。
(額外:boost庫的boost::scoped_ptr也是一個獨占性智能指針,但是它不允許轉(zhuǎn)移所有權(quán),從始而終都只對一個資源負責(zé),它更安全謹慎,但是應(yīng)用的范圍也更狹窄。)
例如:
unique_ptr<string> ps1, ps2; ps1 = demo("hello"); ps2 = move(ps1); ps1 = demo("alexia"); cout << *ps2 << *ps1 << endl;shared_ptr
shared_ptr實現(xiàn)共享式擁有概念。多個智能指針可以指向相同對象,該對象和其相關(guān)資源會在“最后一個引用被銷毀”時候釋放。從名字share就可以看出了資源可以被多個指針共享,它使用計數(shù)機制來表明資源被幾個指針共享。可以通過成員函數(shù)use_count()來查看資源的所有者個數(shù)。除了可以通過new來構(gòu)造,還可以通過傳入auto_ptr, unique_ptr,weak_ptr來構(gòu)造。當我們調(diào)用release()時,當前指針會釋放資源所有權(quán),計數(shù)減一。當計數(shù)等于0時,資源會被釋放。
shared_ptr 是為了解決 auto_ptr 在對象所有權(quán)上的局限性(auto_ptr 是獨占的), 在使用引用計數(shù)的機制上提供了可以共享所有權(quán)的智能指針。
成員函數(shù):
use_count 返回引用計數(shù)的個數(shù)
unique 返回是否是獨占所有權(quán)( use_count 為 1)
swap 交換兩個 shared_ptr 對象(即交換所擁有的對象)
reset 放棄內(nèi)部對象的所有權(quán)或擁有對象的變更, 會引起原有對象的引用計數(shù)的減少
get 返回內(nèi)部對象(指針), 由于已經(jīng)重載了()方法, 因此和直接使用對象是一樣的.如
shared_ptr<int> sp(new int(1));sp 與 sp.get()是等價的。
share_ptr的簡單例子:
int main() {string *s1 = new string("s1");shared_ptr<string> ps1(s1);shared_ptr<string> ps2;ps2 = ps1;cout << ps1.use_count()<<endl; //2cout<<ps2.use_count()<<endl; //2cout << ps1.unique()<<endl; //0string *s3 = new string("s3");shared_ptr<string> ps3(s3);cout << (ps1.get()) << endl; //033AEB48cout << ps3.get() << endl; //033B2C50swap(ps1, ps3); //交換所擁有的對象cout << (ps1.get())<<endl; //033B2C50cout << ps3.get() << endl; //033AEB48cout << ps1.use_count()<<endl; //1cout << ps2.use_count() << endl; //2ps2 = ps1;cout << ps1.use_count()<<endl; //2cout << ps2.use_count() << endl; //2ps1.reset(); //放棄ps1的擁有權(quán),引用計數(shù)的減少cout << ps1.use_count()<<endl; //0cout << ps2.use_count()<<endl; //1 }weak_ptr
share_ptr雖然已經(jīng)很好用了,但是有一點share_ptr智能指針還是有內(nèi)存泄露的情況,當兩個對象相互使用一個shared_ptr成員變量指向?qū)Ψ?#xff0c;會造成循環(huán)引用,使引用計數(shù)失效,從而導(dǎo)致內(nèi)存泄漏。
weak_ptr 是一種不控制對象生命周期的智能指針, 它指向一個 shared_ptr 管理的對象. 進行該對象的內(nèi)存管理的是那個強引用的shared_ptr, weak_ptr只是提供了對管理對象的一個訪問手段。weak_ptr 設(shè)計的目的是為配合 shared_ptr 而引入的一種智能指針來協(xié)助 shared_ptr 工作, 它只可以從一個 shared_ptr 或另一個 weak_ptr 對象構(gòu)造, 它的構(gòu)造和析構(gòu)不會引起引用記數(shù)的增加或減少。weak_ptr是用來解決shared_ptr相互引用時的死鎖問題,如果說兩個shared_ptr相互引用,那么這兩個指針的引用計數(shù)永遠不可能下降為0,資源永遠不會釋放。它是對對象的一種弱引用,不會增加對象的引用計數(shù),和shared_ptr之間可以相互轉(zhuǎn)化,shared_ptr可以直接賦值給它,它可以通過調(diào)用lock函數(shù)來獲得shared_ptr。
class B; //聲明 class A { public:shared_ptr<B> pb_;~A(){cout << "A delete\n";} };class B { public:shared_ptr<A> pa_;~B(){cout << "B delete\n";} };void fun() {shared_ptr<B> pb(new B());shared_ptr<A> pa(new A());cout << pb.use_count() << endl; //1cout << pa.use_count() << endl; //1pb->pa_ = pa;pa->pb_ = pb;cout << pb.use_count() << endl; //2cout << pa.use_count() << endl; //2 }int main() {fun();return 0; }可以看到fun函數(shù)中pa ,pb之間互相引用,兩個資源的引用計數(shù)為2,當要跳出函數(shù)時,智能指針pa,pb析構(gòu)時兩個資源引用計數(shù)會減1,但是兩者引用計數(shù)還是為1,導(dǎo)致跳出函數(shù)時資源沒有被釋放(A、B的析構(gòu)函數(shù)沒有被調(diào)用)運行結(jié)果沒有輸出析構(gòu)函數(shù)的內(nèi)容,造成內(nèi)存泄露。如果把其中一個改為weak_ptr就可以了,我們把類A里面的shared_ptr pb_,改為weak_ptr pb_ ,運行結(jié)果如下:
1 1 1 2 B delete A delete這樣的話,資源B的引用開始就只有1,當pb析構(gòu)時,B的計數(shù)變?yōu)?,B得到釋放,B釋放的同時也會使A的計數(shù)減1,同時pa析構(gòu)時使A的計數(shù)減1,那么A的計數(shù)為0,A得到釋放。
注意:我們不能通過weak_ptr直接訪問對象的方法,比如B對象中有一個方法print(),我們不能這樣訪問,pa->pb_->print(),因為pb_是一個weak_ptr,應(yīng)該先把它轉(zhuǎn)化為shared_ptr,如:
shared_ptr<B> p = pa->pb_.lock(); p->print();weak_ptr 沒有重載*和->但可以使用 lock 獲得一個可用的 shared_ptr 對象. 注意, weak_ptr 在使用前需要檢查合法性.
expired 用于檢測所管理的對象是否已經(jīng)釋放, 如果已經(jīng)釋放, 返回 true; 否則返回 false.
lock 用于獲取所管理的對象的強引用(shared_ptr). 如果 expired 為 true, 返回一個空的 shared_ptr; 否則返回一個 shared_ptr, 其內(nèi)部對象指向與 weak_ptr 相同.
use_count 返回與 shared_ptr 共享的對象的引用計數(shù).
reset 將 weak_ptr 置空.
weak_ptr 支持拷貝或賦值, 但不會影響對應(yīng)的 shared_ptr 內(nèi)部對象的計數(shù).
share_ptr和weak_ptr的核心實現(xiàn)
weakptr的作為弱引用指針,其實現(xiàn)依賴于counter的計數(shù)器類和share_ptr的賦值,構(gòu)造,所以先把counter和share_ptr簡單實現(xiàn)
Counter簡單實現(xiàn)
class Counter { public:Counter() : s(0), w(0){};int s; //share_ptr的引用計數(shù)int w; //weak_ptr的引用計數(shù) };counter對象的目地就是用來申請一個塊內(nèi)存來存引用基數(shù),s是share_ptr的引用計數(shù),w是weak_ptr的引用計數(shù),當w為0時,刪除Counter對象。
share_ptr的簡單實現(xiàn)
template <class T> class WeakPtr; //為了用weak_ptr的lock(),來生成share_ptr用,需要拷貝構(gòu)造用template <class T> class SharePtr { public:SharePtr(T *p = 0) : _ptr(p){cnt = new Counter();if (p)cnt->s = 1;cout << "in construct " << cnt->s << endl;}~SharePtr(){release();}SharePtr(SharePtr<T> const &s){cout << "in copy con" << endl;_ptr = s._ptr;(s.cnt)->s++;cout << "copy construct" << (s.cnt)->s << endl;cnt = s.cnt;}SharePtr(WeakPtr<T> const &w) //為了用weak_ptr的lock(),來生成share_ptr用,需要拷貝構(gòu)造用{cout << "in w copy con " << endl;_ptr = w._ptr;(w.cnt)->s++;cout << "copy w construct" << (w.cnt)->s << endl;cnt = w.cnt;}SharePtr<T> &operator=(SharePtr<T> &s){if (this != &s){release();(s.cnt)->s++;cout << "assign construct " << (s.cnt)->s << endl;cnt = s.cnt;_ptr = s._ptr;}return *this;}T &operator*(){return *_ptr;}T *operator->(){return _ptr;}friend class WeakPtr<T>; //方便weak_ptr與share_ptr設(shè)置引用計數(shù)和賦值protected:void release(){cnt->s--;cout << "release " << cnt->s << endl;if (cnt->s < 1){delete _ptr;if (cnt->w < 1){delete cnt;cnt = NULL;}}}private:T *_ptr;Counter *cnt; };share_ptr的給出的函數(shù)接口為:構(gòu)造,拷貝構(gòu)造,賦值,解引用,通過release來在引用計數(shù)為0的時候刪除_ptr和cnt的內(nèi)存。
weak_ptr簡單實現(xiàn)
template <class T> class WeakPtr { public: //給出默認構(gòu)造和拷貝構(gòu)造,其中拷貝構(gòu)造不能有從原始指針進行構(gòu)造WeakPtr(){_ptr = 0;cnt = 0;}WeakPtr(SharePtr<T> &s) : _ptr(s._ptr), cnt(s.cnt){cout << "w con s" << endl;cnt->w++;}WeakPtr(WeakPtr<T> &w) : _ptr(w._ptr), cnt(w.cnt){cnt->w++;}~WeakPtr(){release();}WeakPtr<T> &operator=(WeakPtr<T> &w){if (this != &w){release();cnt = w.cnt;cnt->w++;_ptr = w._ptr;}return *this;}WeakPtr<T> &operator=(SharePtr<T> &s){cout << "w = s" << endl;release();cnt = s.cnt;cnt->w++;_ptr = s._ptr;return *this;}SharePtr<T> lock(){return SharePtr<T>(*this);}bool expired(){if (cnt){if (cnt->s > 0){cout << "empty" << cnt->s << endl;return false;}}return true;}friend class SharePtr<T>; //方便weak_ptr與share_ptr設(shè)置引用計數(shù)和賦值protected:void release(){if (cnt){cnt->w--;cout << "weakptr release" << cnt->w << endl;if (cnt->w < 1 && cnt->s < 1){//delete cnt;cnt = NULL;}}}private:T *_ptr;Counter *cnt; };weak_ptr一般通過share_ptr來構(gòu)造,通過expired函數(shù)檢查原始指針是否為空,lock來轉(zhuǎn)化為share_ptr。
總結(jié)
以上是生活随笔為你收集整理的详解C++11智能指针的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: opencv-linux安装
- 下一篇: 普通卷积armv7-neon指令集实现—