【Smart_Point】C/C++ 中智能指针
C++11智能指針
目錄
C++11智能指針
1.1 C++11智能指針介紹
1.2 為什么要使用智能指針
1.2.1 auto_ptr(C++98的方案,C++11已經拋棄)采用所有權模式。
1.2.2 unique_ptr
1.2.4 weak_ptr
1.3.1 Counter簡單實現
1.3.3 weak_ptr簡單實現
1.4 分清楚場合應該使用哪種類型的智能指針;
C++里面的四個智能指針: auto_ptr, unique_ptr,shared_ptr, weak_ptr 其中后三個是C++11支持,并且第一個已經被C++11棄用。
1.1 C++11智能指針介紹
智能指針主要用于管理在堆上分配的內存,它將普通的指針封裝為一個棧對象。當棧對象的生存周期結束后,會在析構函數中釋放掉申請的內存,從而防止內存泄漏。C++ 11中最常用的智能指針類型為shared_ptr,它采用引用計數的方法,記錄當前內存資源被多少個智能指針引用。該引用計數的內存在堆上分配。當新增一個時引用計數加1,當過期時引用計數減一。只有引用計數為0時,智能指針才會自動釋放引用的內存資源。對shared_ptr進行初始化時不能將一個普通指針直接賦值給智能指針,因為一個是指針,一個是類。可以通過make_shared函數或者通過構造函數傳入普通指針。并可以通過get函數獲得普通指針。
1.2 為什么要使用智能指針
智能指針的作用是管理一個指針,因為存在以下這種情況:申請的空間在函數結束時忘記釋放,造成內存泄漏。使用智能指針可以很大程度上的避免這個問題,因為智能指針是一個類,當超出了類的實例對象的作用域時,會自動調用對象的析構函數,析構函數會自動釋放資源。所以智能指針的作用原理就是在函數結束時自動釋放內存空間,不需要手動釋放內存空間。
1.2.1 auto_ptr(C++98的方案,C++11已經拋棄)采用所有權模式。
auto_ptr<string> p1 (new string ("I reigned lonely as a cloud."));
auto_ptr<string> p2;
p2 = p1; //auto_ptr不會報錯.
此時不會報錯,p2剝奪了p1的所有權,但是當程序運行時訪問p1將會報錯。所以auto_ptr的缺點是:存在潛在的內存崩潰問題!
std::auto_ptr 真正讓人容易誤用的地方是其不常用的復制語義,即當復制一個 std::auto_ptr 對象時(拷貝復制或 operator = 復制),原對象所持有的堆內存對象也會轉移給復制出來的對象。示例代碼如下:
#include <iostream>
#include <memory>
?
int main()
{//測試拷貝構造std::auto_ptr<int> sp1(new int(8));std::auto_ptr<int> sp2(sp1);if (sp1.get() != NULL){std::cout << "sp1 is not empty." << std::endl;}else{std::cout << "sp1 is empty." << std::endl;}
?if (sp2.get() != NULL){std::cout << "sp2 is not empty." << std::endl;}else{std::cout << "sp2 is empty." << std::endl;}
?//測試賦值構造std::auto_ptr<int> sp3(new int(8));std::auto_ptr<int> sp4;sp4 = sp3;if (sp3.get() != NULL){std::cout << "sp3 is not empty." << std::endl;}else{std::cout << "sp3 is empty." << std::endl;}
?if (sp4.get() != NULL){std::cout << "sp4 is not empty." << std::endl;}else{std::cout << "sp4 is empty." << std::endl;}
?return 0;
}
上述代碼中分別利用拷貝構造(sp1 => sp2)和 賦值構造(sp3 => sp4)來創建新的 std::auto_ptr 對象,因此 sp1 持有的堆對象被轉移給 sp2,sp3 持有的堆對象被轉移給 sp4。我們得到程序執行結果如下:
[root@iZ238vnojlyZ testx]# g++ -g -o test_auto_ptr test_auto_ptr.cpp
[root@iZ238vnojlyZ testx]# ./test_auto_ptr
sp1 is empty.
sp2 is not empty.
sp3 is empty.
sp4 is not empty.
由于 std::auto_ptr 這種不常用的復制語義,我們應該避免在 stl 容器中使用 std::auto_ptr,例如我們絕不應該寫出如下代碼:
std::vector<std::auto_ptr<int>> myvectors;
當用算法對容器操作的時候(如最常見的容器元素遍歷),很難避免不對容器中的元素實現賦值傳遞,這樣便會使容器中多個元素被置為空指針,這不是我們想看到的,會造成很多意想不到的錯誤。
以史為鑒,作為 std::auto_ptr 的替代者 std::unique_ptr 吸取了這個經驗教訓。下文會來詳細介紹。
正因為 std::auto_ptr 的設計存在如此重大缺陷,C++11 標準在充分借鑒和吸收了 boost 庫中智能指針的設計思想,引入了三種類型的智能指針,即 std::unique_ptr、std::shared_ptr 和 std::weak_ptr。
boost 還有 scoped_ptr,C++11 并沒有全部照搬,而是選擇了三個最實用的指針類型。在 C++11 中可以通過 std::unique_ptr 達到與 boost::scoped_ptr 一樣的效果。
1.2.2 unique_ptr
(替換auto_ptr)unique_ptr實現獨占式擁有或嚴格擁有概念,保證同一時間內只有一個智能指針可以指向該對象。它對于避免資源泄露(例如“以new創建對象后因為發生異常而忘記調用delete”)特別有用。 與shared_ptr不同,某一時刻,只能有一個unique_ptr指向一個給定的對象。因此,當unique_ptr被銷毀,它所指的對象也會被銷毀。
std::unique_ptr 對其持有的堆內存具有唯一擁有權,也就是說引用計數永遠是 1,std::unique_ptr 對象銷毀時會釋放其持有的堆內存。可以使用以下方式初始化一個 std::unique_ptr 對象:
//初始化方式1
std::unique_ptr<int> sp1(new int(123));
?
//初始化方式2
std::unique_ptr<int> sp2;
sp2.reset(new int(123));
?
//初始化方式3
std::unique_ptr<int> sp3 = std::make_unique<int>(123);
你應該盡量使用初始化方式 3 的方式去創建一個 std::unique_ptr 而不是方式 1 和 2,因為形式 3 更安全,原因 Scott Meyers 在其《Effective Modern C++》中已經解釋過了,有興趣的讀者可以閱讀此書相關章節。
令很多人對 C++11 規范不滿的地方是,C++11 新增了 std::make_shared() 方法創建一個 std::shared_ptr 對象,卻沒有提供相應的 std::make_unique() 方法創建一個 std::unique_ptr 對象,這個方法直到 C++14 才被添加進來。當然,在 C++11 中你很容易實現出這樣一個方法來:
template<typename T, typename... Ts>
std::unique_ptr<T> make_unique(Ts&& ...params)
{return std::unique_ptr<T>(new T(std::forward<Ts>(params)...));
}
鑒于 std::auto_ptr 的前車之鑒,std::unique_ptr 禁止復制語義,為了達到這個效果,std::unique_ptr 類的拷貝構造函數和賦值運算符(operator =)被標記為 delete。
template <class T>
class unique_ptr
{//省略其他代碼...
?//拷貝構造函數和賦值運算符被標記為deleteunique_ptr(const unique_ptr&) = delete;unique_ptr& operator=(const unique_ptr&) = delete;
};//禁止拷貝復制和operattor=復制,允許所有權轉移
因此,下列代碼是無法通過編譯的:
std::unique_ptr<int> sp1(std::make_unique<int>(123));;
?
//以下代碼無法通過編譯
//std::unique_ptr<int> sp2(sp1);
std::unique_ptr<int> sp3;
//以下代碼無法通過編譯
//sp3 = sp1;
禁止復制語義也存在特例,即可以通過一個函數返回一個 std::unique_ptr:
#include <memory>std::unique_ptr<int> func(int val)
{std::unique_ptr<int> up(new int(val));return up;
}int main()
{std::unique_ptr<int> sp1 = func(123);return 0;
}
上述代碼從 func 函數中得到一個 std::unique_ptr 對象,然后返回給 sp1。
既然 std::unique_ptr 不能復制,那么如何將一個 std::unique_ptr 對象持有的堆內存轉移給另外一個呢?答案是使用移動構造,示例代碼如下
#include <memory>int main()
{std::unique_ptr<int> sp1(std::make_unique<int>(123));std::unique_ptr<int> sp2(std::move(sp1));std::unique_ptr<int> sp3;sp3 = std::move(sp2);return 0;
}
以上代碼利用 std::move 將 sp1 持有的堆內存(值為 123)轉移給 sp2,再把 sp2 轉移給 sp3。最后,sp1 和 sp2 不再持有堆內存的引用,變成一個空的智能指針對象。并不是所有的對象的 std::move 操作都有意義,只有實現了移動構造函數(Move Constructor)或移動賦值運算符(operator =)的類才行,而 std::unique_ptr 正好實現了這二者,以下是實現偽碼:
template<typename T, typename Deletor>
class unique_ptr
{//其他函數省略...
public:unique_ptr(unique_ptr&& rhs){this->m_pT = rhs.m_pT;//源對象釋放rhs.m_pT = nullptr;}unique_ptr& operator=(unique_ptr&& rhs){this->m_pT = rhs.m_pT;//源對象釋放rhs.m_pT = nullptr;return *this;}private:T* m_pT;
};
這是 std::unique_ptr 具有移動語義的原因。
std::unique_ptr 不僅可以持有一個堆對象,也可以持有一組堆對象,示例如下:
#include <iostream>
#include <memory>int main()
{//創建10個int類型的堆對象//形式1std::unique_ptr<int[]> sp1(new int[10]);//形式2std::unique_ptr<int[]> sp2;sp2.reset(new int[10]);//形式3std::unique_ptr<int[]> sp3(std::make_unique<int[]>(10));for (int i = 0; i < 10; ++i){sp1[i] = i;sp2[i] = i;sp3[i] = i;}for (int i = 0; i < 10; ++i){std::cout << sp1[i] << ", " << sp2[i] << ", " << sp3[i] << std::endl;}return 0;
}
程序執行結果如下:
0, 0, 0
1, 1, 1
2, 2, 2
3, 3, 3
4, 4, 4
5, 5, 5
6, 6, 6
7, 7, 7
8, 8, 8
9, 9, 9
std::shared_ptr 和 std::weak_ptr 也可以持有一組堆對象,用法與 std::unique_ptr 相同,下文不再贅述。
采用所有權模式,還是上面那個例子
unique_ptr<string> p3 (new string ("auto")); //#4
unique_ptr<string> p4; //#5
p4 = p3;//此時會報錯!!
編譯器認為p4=p3非法,避免了p3不再指向有效數據的問題。嘗試復制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),這可能導致危害。而#2不會留下懸掛的unique_ptr,因為它調用 unique_ptr 的構造函數,該構造函數創建的臨時對象在其所有權讓給 pu3 后就會被銷毀。這種隨情況而已的行為表明,unique_ptr 優于允許兩種賦值的auto_ptr 。
注:如果確實想執行類似與#1的操作,要安全的重用這種指針,可給它賦新值。C++有一個標準庫函數std::move(),讓你能夠將一個unique_ptr賦給另一個。盡管轉移所有權后 還是有可能出現原有指針調用(調用就崩潰)的情況。但是這個語法能強調你是在轉移所有權,讓你清晰的知道自己在做什么,從而不亂調用原有指針。
額外:boost庫的boost::scoped_ptr也是一個獨占性智能指針,但是它不允許轉移所有權,從始而終都只對一個資源負責,它更安全謹慎,但是應用的范圍也更狹窄。
unique_ptr<string> ps1, ps2;
ps1 = demo("hello");
ps2 = move(ps1);
ps1 = demo("alexia");
cout << *ps2 << *ps1 << endl;
1.2.3 shared_ptr
shared_ptr實現共享式擁有概念。多個智能指針可以指向相同對象,該對象和其相關資源會在“最后一個引用被銷毀”時候釋放。從名字share就可以看出了資源可以被多個指針共享,它使用計數機制來表明資源被幾個指針共享。可以通過成員函數use_count()來查看資源的所有者個數。除了可以通過new來構造,還可以通過傳入auto_ptr, unique_ptr,weak_ptr來構造。當我們調用release()時,當前指針會釋放資源所有權,計數減一。當計數等于0時,資源會被釋放。
td::unique_ptr 對其持有的資源具有獨占性,而 std::shared_ptr 持有的資源可以在多個 std::shared_ptr 之間共享,每多一個 std::shared_ptr 對資源的引用,資源引用計數將增加 1,每一個指向該資源的 std::shared_ptr 對象析構時,資源引用計數減 1,最后一個 std::shared_ptr 對象析構時,發現資源計數為 0,將釋放其持有的資源。多個線程之間,遞增和減少資源的引用計數是安全的。(注意:這不意味著多個線程同時操作 std::shared_ptr 引用的對象是安全的)。std::shared_ptr 提供了一個 use_count() 方法來獲取當前持有資源的引用計數。除了上面描述的,std::shared_ptr 用法和 std::unique_ptr 基本相同。
shared_ptr 是為了解決 auto_ptr 在對象所有權上的局限性(auto_ptr 是獨占的), 在使用引用計數的機制上提供了可以共享所有權的智能指針。
成員函數:
std::shared_ptr<int> sp1(new int(123));
//
std::shared_ptr<int> sp2;
sp2.reset(new int(123));
//
std::shared+ptr<int> sp3;
sp3=std::make_shared<int>(123);
和 std::unique_ptr 一樣,你應該優先使用 std::make_shared 去初始化一個 std::shared_ptr 對象。
再來看另外一段代碼:
#include <iostream>
#include <memory>class A
{
public:A(){std::cout << "A constructor" << std::endl;}~A(){std::cout << "A destructor" << std::endl;}
};int main()
{{//初始化方式1std::shared_ptr<A> sp1(new A());std::cout << "sp1 use count: " << sp1.use_count() << std::endl;//初始化方式2std::shared_ptr<A> sp2(sp1);std::cout << "sp2 use count: " << sp1.use_count() << std::endl;sp2.reset();std::cout << "sp2 reset use count: " << sp1.use_count() << std::endl;{std::shared_ptr<A> sp3 = sp1;std::cout << "sp3 = sp1 use count: " << sp1.use_count() << std::endl;}std::cout << "use count: " << sp1.use_count() << std::endl;}return 0;
}
-
上述代碼 22 行 sp1 構造時,同時觸發對象 A 的構造,因此 A 的構造函數會執行;
-
此時只有一個 sp1 對象引用 22 行 new 出來的 A 對象(為了敘述方便,下文統一稱之為資源對象 A),因此代碼 24 行打印出來的引用計數值為 1;
-
代碼 27 行,利用 sp1 拷貝一份 sp2,導致代碼 28 行打印出來的引用計數為 2;
-
代碼 30 行調用 sp2 的 reset() 方法,sp2 釋放對資源對象 A 的引用,因此代碼 31 行打印的引用計數值再次變為 1;
-
代碼 34 行 利用 sp1 再次 創建 sp3,因此代碼 35 行打印的引用計數變為 2;
-
程序執行到 36 行以后,sp3 出了其作用域被析構,資源 A 的引用計數遞減 1,因此 代碼 38 行打印的引用計數為 1;
-
程序執行到 39 行以后,sp1 出了其作用域被析構,在其析構時遞減資源 A 的引用計數至 0,并析構資源 A 對象,因此類 A 的析構函數被調用。
A constructor sp1 use count: 1 sp2 use count: 2 sp2 reset use count: 1 sp3 = sp1 use count: 2 use count: 1 A destructor
所以整個程序的執行結果如下:
use_count 返回引用計數的個數unique 返回是否是獨占所有權( use_count 為 1)swap 交換兩個 `shared_ptr` 對象(即交換所擁有的對象)reset 放棄內部對象的所有權或擁有對象的變更, 會引起原有對象的引用計數的減少get 返回內部對象(指針), 由于已經重載了()方法, 因此和直接使用對象是一樣的.如
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的擁有權,引用計數的減少cout << ps1.use_count()<<endl; //0cout << ps2.use_count()<<endl; //1
}
1.2.4 weak_ptr
share_ptr雖然已經很好用了,但是有一點share_ptr智能指針還是有內存泄露的情況,當兩個對象相互使用一個shared_ptr成員變量指向對方,會造成循環引用,使引用計數失效,從而導致內存泄漏。
weak_ptr 是一種不控制對象生命周期的智能指針, 它指向一個 shared_ptr 管理的對象. 進行該對象的內存管理的是那個強引用的shared_ptr, weak_ptr只是提供了對管理對象的一個訪問手段。weak_ptr 設計的目的是為配合 shared_ptr 而引入的一種智能指針來協助 shared_ptr 工作, 它只可以從一個 shared_ptr 或另一個 weak_ptr 對象構造, 它的構造和析構不會引起引用記數的增加或減少。weak_ptr是用來解決shared_ptr相互引用時的死鎖問題,如果說兩個shared_ptr相互引用,那么這兩個指針的引用計數永遠不可能下降為0,資源永遠不會釋放。它是對對象的一種弱引用,不會增加對象的引用計數,和shared_ptr之間可以相互轉化,shared_ptr可以直接賦值給它,它可以通過調用lock函數來獲得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函數中pa ,pb之間互相引用,兩個資源的引用計數為2,當要跳出函數時,智能指針pa,pb析構時兩個資源引用計數會減1,但是兩者引用計數還是為1,導致跳出函數時資源沒有被釋放(A、B的析構函數沒有被調用)運行結果沒有輸出析構函數的內容,造成內存泄露。如果把其中一個改為weak_ptr就可以了,我們把類A里面的shared_ptr pb,改為weak_ptr`pb` ,運行結果如下:
1
1
1
2
B delete
A delete
這樣的話,資源B的引用開始就只有1,當pb析構時,B的計數變為0,B得到釋放,B釋放的同時也會使A的計數減1,同時pa析構時使A的計數減1,那么A的計數為0,A得到釋放。
注意:我們不能通過weak_ptr直接訪問對象的方法,比如B對象中有一個方法print(),我們不能這樣訪問,pa->pb_->print(),因為pb_是一個weak_ptr,應該先把它轉化為shared_ptr,如:
shared_ptr<B> p = pa->pb_.lock();
p->print();
weak_ptr 沒有重載*和->但可以使用 lock 獲得一個可用的 shared_ptr 對象. 注意, weak_ptr 在使用前需要檢查合法性.
expired 用于檢測所管理的對象是否已經釋放, 如果已經釋放, 返回 true; 否則返回 false.
lock 用于獲取所管理的對象的強引用(shared_ptr). 如果 expired 為 true, 返回一個空的 shared_ptr; 否則返回一個 shared_ptr, 其內部對象指向與 weak_ptr 相同.
use_count 返回與 shared_ptr 共享的對象的引用計數.
reset 將 weak_ptr 置空.
weak_ptr 支持拷貝或賦值, 但不會影響對應的 shared_ptr 內部對象的計數.
1.3 share_ptr和weak_ptr的核心實現
weak_ptr的作為弱引用指針,其實現依賴于counter的計數器類和share_ptr的賦值,構造,所以先把counter和share_ptr簡單實現
1.3.1 Counter簡單實現
class Counter
{
public:Counter() : s(0), w(0){};int s; //share_ptr的引用計數int w; //weak_ptr的引用計數
};
counter對象的目地就是用來申請一個塊內存來存引用基數,s是share_ptr的引用計數,w是weak_ptr的引用計數,當w為0時,刪除Counter對象。
1.3.2 share_ptr的簡單實現
template <class T>
class WeakPtr; //為了用weak_ptr的lock(),來生成share_ptr用,需要拷貝構造用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用,需要拷貝構造用{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設置引用計數和賦值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的給出的函數接口為:構造,拷貝構造,賦值,解引用,通過release來在引用計數為0的時候刪除_ptr和cnt的內存。
1.3.3 weak_ptr簡單實現
template <class T>
class WeakPtr
{
public: //給出默認構造和拷貝構造,其中拷貝構造不能有從原始指針進行構造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設置引用計數和賦值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來構造,通過expired函數檢查原始指針是否為空,lock來轉化為share_ptr。
不過感覺最后的SharePtr有個地方可以改進下: SharePtr在析構時釋放_ptr和cnt,可能會導致釋放cnt不成功。 代碼里cnt的釋放取決于cnt->w, 而cnt->w是否為0取決于WeakPtr的析構。 如果SharePtr先于WeakPtr析構, 此時cnt->w 大于0,SharePtr無法釋放cnt
這個地方感覺可以不用判斷cnt->w,直接delete cnt; cnt->s都為0了,不會有別的地方再使用管理的對象_ptr了,cnt的存在也就沒意義了。
void release()
{cnt->s--;cout << "release " << cnt->s << endl;if (cnt->s < 1){delete _ptr;if (cnt->w < 1) //取消這個判斷{delete cnt;cnt = NULL;}}
}
1.4 分清楚場合應該使用哪種類型的智能指針;
1.4.1 std::unique_ptr:
1 小巧、高速、具備只移型別的智能指針,對托管資源實施專屬所有權語義。
2 默認地,資源析構采用delete運算符來實現,但可以指定自定義刪除器。有狀態的刪除器和采用函數指針實現的刪除器會增加std::unique_ptr型別的對象尺寸
3 將std::unique_ptr 轉換成std::shared_ptr是容易實現的
1.4.2 std::shared_ptr:
1 提供方便的手段,實現了任意資源在共享所有權語義下進行生命周期管理的垃圾回收
2 與std::unique_*ptr* 相比,std::shared_ptr的尺寸通常是裸指針尺寸的兩倍,它還會帶來控制塊的開銷,并要求原子化的引用計數操作。
3 默認的資源析構通過delete運算符進行,但同時也支持定制刪除器。刪除器的型別對std::shared_ptr的型別沒有影響。
4 避免使用裸指針型別的變量來創建 std::shared_ptr 指針
1.4.3 std::weak_ptr:
1 使用std::weakptr 來代替可能空懸的std::shared_ptr
2 std::weak_ptr 可能的用武之地包括緩存,觀察者列表,以及避免std::shared_ptr 指針環路。
看看大師的總結,完美!!
具體到完全代替裸指針,恐怕也要再掂量掂量。
下面寫一些劣勢:
std::shared_ptr 會增加內存開銷,復制的時候cpu消耗提高【原子count操作】
std::unique_ptr 內存占用小,幾乎可以媲美裸指針;但是它畢竟是一個類,使用的時候,不能復制,導致你一個作用域內只能有一個可用的實例【類似rust的所有權吧,你用起來有點束手束腳】;
std::weak_ptr 必須跟std::shared_ptr配合使用。
優勢:
省去你自己判斷啥時候該釋放資源【異步回調時候智能指針可以完美避免手動控制生命周期;enable_shared_frome_this 已經可以算是一種特別的編程技巧了】
裸指針的操作習慣
1.對于性能和內存使用有嚴格要求的場景,不要過于依賴智能指針【比如嵌入式這些的,實際上C+class就夠了】
2.對于類型不敏感的數據【也就是內存了】,可以考慮使用std::array或者std::vector等。因為這個時候,你實際上就是C的操作,類型對于該內存僅僅起到一個布局描述的作用,頻繁的類型轉換【非繼承關系】、字段偏移等操作,用智能指針也沒有什么好處【因為你還是會拿到裸指針去操作】
3.其他的對類型敏感,或者對作用域敏感的數據內存,可以都考慮使用智能指針。局部作用域使用uniqe_ptr , 多作用域的使用shared_ptr,緩存可能失效的情況下使用weak_ptr。
一般應用,除了容器,幾乎一上來全部使用uniqe_ptr,當需要拋出一個副本的時候,使用shared_ptr。當功能完成的時候,哪個內存是全局生命周期,改成裸指針【全局裸指針我都不判空】。如果該項目不是那么重要,甚至我都會全部用shared_ptr,不用關心性能問題,因為C++本身的編譯性能已經很高了,隨便寫寫性能就夠了,只要不飛,內存泄漏不是問題。
當我要去判斷某一個內存之后的操作會失效,但是不知道什么時候失效的時候,我使用weak_ptr和shared_ptr。通過weak_ptr接口可以線程安全的獲取我之前的智能指針是否還生效。【這個時候,裸指針,幾乎是沒有辦法的了,很容易出現野指針】
參考: https://blog.csdn.net/Darlingqiang/article/details/114065349?spm=1001.2014.3001.5501
https://zhuanlan.zhihu.com/p/29628938
https://www.zhihu.com/question/319277442/answer/1517987598
https://www.zhihu.com/question/319277442/answer/1517987598
https://blog.csdn.net/H_Strong/article/details/88754979?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161544736616780274137097%2522%252C%2522scm%2522%253A%252220140713.130102334..%2522%257D&request_id=161544736616780274137097&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~top_click~default-1-88754979.first_rank_v2_pc_rank_v29_10&utm_term=%E6%99%BA%E8%83%BD%E6%8C%87%E9%92%88
總結
以上是生活随笔為你收集整理的【Smart_Point】C/C++ 中智能指针的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 我们来相聚我们来珍惜是什么歌啊
- 下一篇: 【C++】C/C++ 中default/