《Effective Modern C++》item 21: Prefer std::make_unique and std::make_shared to direct use of new

                                                                 希望能使一個病入膏肓的人起死回生------〔古羅馬〕奧維德


---直到c++14,std::make_unique函數纔出現,但是用戶使用c++11的話可以自己實現一個:

Let’s begin by leveling the playing field for std::make_unique and std::make_shared.   std::make_shared is part of C++11, but, sadly, std::make_unique isn’t. It joined the Standard Library as of C++14. If you’re using C++11,never fear, because a basic version of std::make_unique is easy to write yourself. Here, look:

https://isocpp.org/blog/2013/04/n3656-make-unique-revision-1

https://isocpp.org/get-started

---三個智能指針相關的make函數:

 

---建議使用make_xx函數來構造智能指針的原因(1):使用new的話會造成類型重複出現在代碼中,造成

代碼冗餘:

---建議使用make_xx函數來構造智能指針的原因(2):可以防止異常產生時,導致new出來的資源不能被合理地託管(memory leak),

例如,舉例,processWidget( std::shared_ptr<Widget>(new Widget), computePriority()); 執行該函數時,編譯器會先運算

出其入參的值,可能會出現如下的執行順序: 先執行new widige, 再執行 computePriority(),最後執行std::shared_ptr<Widget>的

構造函數,這樣的話,如果在第二部執行computePriority函數時出現異常,那麼第一步中被new出來的資源就沒有人託管了,導致資源泄漏, 而使用make_shared函數可以避免這個問題啦。

--使用make_shared函數可以避免這個問題:

--對於unique_ptr也是一樣的道理哦:

---建議使用make_xx函數來構造智能指針的原因(3):improve efficiency,  例如,使用make函數時,一次性給分配

一個空間用來存儲對象和智能指針的計數資源!



---不適合使用make_xx函數的地方(1):make函數不支持custom deleter

---不適合使用make_xx函數的地方(2):

  需要先學習item7

---不適合使用make_xx函數的地方(3):有些類自定義了new ,delete操作(運算符重載吧):

 



--對於shared_ptr,其需要一塊空間來存儲引用計數,原來該空間也存儲着相應的weak_ptr的個數!!

使用make_x來創建智能指針時,一次性分配一個大內存,其中存着被託管的對象以及control block(即引用計數),

但是,這塊大內存直到所有相關的shared_ptr以及weak_ptr都消失後纔會被釋放:

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章