聊聊智能指針 auto_ptr、shared_ptr、weak_ptr和unique_ptr


本文為轉載:https://www.cnblogs.com/zeppelin5/p/10083597.html,對作者有些地方做了修正。

手寫代碼是理解C++的最好辦法,以幾個例子說明C++四個智能指針的用法,轉載請注明出處。

一、auto_ptr

  auto_ptr這是C++98標准下的智能指針,現在常常已經被C++標准的其他智能指針取代。它的缺點是在轉移所有權后會使運行期不安全。C++11新標准,用unique_ptr來代替auto_ptr原有功能,其用法介紹見第四部分unique_ptr。

 1 #include <iostream>
 2 #include <memory>
 3 #include <string>
 4 using namespace std;
 5 
 6 void main(){
 7     auto_ptr<string> country[5] =
 8     {
 9         auto_ptr<string>(new string("USA")),
10         auto_ptr<string>(new string("CHN")),
11         auto_ptr<string>(new string("RUS")),
12         auto_ptr<string>(new string("FRA")),
13         auto_ptr<string>(new string("GRB"))
14     };
15 
16     auto_ptr<string> pwin;
17     pwin = country[2]; //將所有權從country[2]轉讓給pwin,此時country[2]不再引用該字符串從而變成空指針,在運行到循環時就會崩潰
18 
19     for (int i = 0; i < 5; ++i)
20         cout << *country[i] << endl;//運行到[2]時崩潰,因為country[2]為空
21     cout << "The best is " << *pwin << endl;
22 
23     system("pause");
24 }

二、share_ptr

  share_ptr是C++11新添加的智能指針,它限定的資源可以被多個指針共享。

用法見下例:

 1 #include <iostream>
 2 #include <memory>
 3 #include <string>
 4 using namespace std;
 5 
 6 void fun(){
 7     shared_ptr<string> pa(new string("CHN"));
 8     shared_ptr<string> pb(new string("USA"));
 9     cout << "*pa " << *pa << endl;//CHN
10     cout << "pa.use_count " << pa.use_count() << endl;//1
11     cout << "*pb " << *pb << endl;//USA
12     cout << "pb.use_count " << pb.use_count() << endl;//1
13 
14     pa = pb;
15     cout << *pa << endl;//USA
16     cout << "pa.use_count " << pa.use_count() << endl;//2:pa和pb指向同一個資源USA了,該資源的計數為2,所以pb、pb都輸出2
17     cout << "pb.use_count " << pb.use_count() << endl;//2
18 
19     pa.reset();
20     pb.reset();
21     cout << "pa.use_count " << pa.use_count() << endl;//0
22     cout << "pb.use_count " << pb.use_count() << endl;//0
23 }
24 
25 void main()
26 {
27     fun();
28     system("pause");
29 }

與數組相結合應用,見另一個例子:

 1 #include <iostream>
 2 #include <memory>
 3 #include <string>
 4 using namespace std;
 5 
 6 void main(){
 7     shared_ptr<string> country[5] =
 8     {
 9         shared_ptr<string>(new string("USA")),
10         shared_ptr<string>(new string("CHN")),
11         shared_ptr<string>(new string("RUS")),
12         shared_ptr<string>(new string("FRA")),
13         shared_ptr<string>(new string("GRB"))
14     };
15 
16     shared_ptr<string> pwin;
17     cout << pwin.use_count() << endl;//輸出0
18     pwin = country[2]; 
19     /*使用shared_ptr時運行正常,因為shared_ptr采用引用計數,pwin和films[2]都指向同一塊內存,
20     在釋放空間時因為事先要判斷引用計數值的大小因此不會出現多次刪除一個對象的錯誤。
21 
22     從名字share就可以看出了資源可以被多個指針共享,它使用計數機制來表明資源被幾個指針共享。
23     可以通過成員函數use_count()來查看資源的所有者個數。
24     */
25     cout << pwin.use_count() << endl;//輸出2
26 
27     for (int i = 0; i < 5; ++i)
28         cout << *country[i] << endl;//對比auto_ptr,這里就不會崩潰,正常的輸出所有的string字符串。
29     cout << "The best is " << *pwin << endl;
30 
31     system("pause");
32 }

三、weak_ptr

  weak_ptr是一種用於解決shared_ptr相互引用時產生死鎖問題的智能指針。如果有兩個shared_ptr相互引用,那么這兩個shared_ptr指針的引用計數永遠不會下降為0,資源永遠不會釋放。weak_ptr是對對象的一種弱引用,它不會增加對象的use_count,weak_ptr和shared_ptr可以相互轉化,shared_ptr可以直接賦值給weak_ptr,weak_ptr也可以通過調用lock函數來獲得shared_ptr。

  先看一下兩個shared_ptr指針互相引用導致的資源釋放失敗的例子:

 1 #include <iostream>
 2 #include <memory>
 3 #include <string>
 4 using namespace std;
 5 
 6 class B;
 7 class A
 8 {
 9 public:
10     shared_ptr<B> pb_;
11     ~A()
12     {
13         cout << "A delete\n";
14     }
15 };
16 class B
17 {
18 public:
19     shared_ptr<A> pa_;
20     ~B()
21     {
22         cout << "B delete\n";
23     }
24 };
25 
26 void fun(){
27     shared_ptr<B> pb(new B());
28     cout << "pb.use_count " << pb.use_count() << endl;//1
29     shared_ptr<A> pa(new A());
30     cout << "pa.use_count " << pa.use_count() << endl;//1
31 
32     pb->pa_ = pa;
33     cout << "pb.use_count " << pb.use_count() << endl;//1
34     cout << "pa.use_count " << pa.use_count() << endl;//2
35     pa->pb_ = pb;
36     cout << "pb.use_count " << pb.use_count() << endl;//2:由於share_ptr是共享資源,所以pb所指向的資源的引用計數也會加1
37     cout << "pa.use_count " << pa.use_count() << endl;//2
38 }//程序結束時,沒有調用A和B的析構函數
39 
40 void main()
41 {
42     fun();
43     system("pause");
44 }

而使用weak_ptr:把A中的shared_ptr<B> pb_改為weak_ptr<B> pb_weak,這樣改為了弱引用,傳遞時不會增加pb引用計數use_count()的值,所以最終能夠使A、B資源正常釋放:

 1 #include <iostream>
 2 #include <memory>
 3 #include <string>
 4 using namespace std;
 5 
 6 class B;
 7 class A
 8 {
 9 public:
10     weak_ptr<B> pb_weak;
11     ~A()
12     {
13         cout << "A delete\n";
14     }
15 };
16 class B
17 {
18 public:
19     shared_ptr<A> pa_;
20     ~B()
21     {
22         cout << "B delete\n";
23     }
24     void print(){
25         cout << "This is B" << endl;
26     }
27 };
28 
29 void fun(){
30     shared_ptr<B> pb(new B());
31     cout << "pb.use_count " << pb.use_count() << endl;//1
32     shared_ptr<A> pa(new A());
33     cout << "pa.use_count " << pa.use_count() << endl;//1
34 
35     pb->pa_ = pa;
36     cout << "pb.use_count " << pb.use_count() << endl;//1
37     cout << "pa.use_count " << pa.use_count() << endl;//2
38 
39     pa->pb_weak = pb;
40     cout << "pb.use_count " << pb.use_count() << endl;//1:弱引用不會增加所指資源的引用計數use_count()的值
41     cout << "pa.use_count " << pa.use_count() << endl;//2
42 
43     shared_ptr<B> p = pa->pb_weak.lock();
44     p->print();//不能通過weak_ptr直接訪問對象的方法,須先轉化為shared_ptr
45     cout << "pb.use_count " << pb.use_count() << endl;//2
46     cout << "pa.use_count " << pa.use_count() << endl;//2
47 }//函數結束時,正確的情況下,應該調用A和B的析構函數
48 
49 /*資源B的引用計數一直就只有1,當pb析構時,B的計數減一,變為0,B得到釋放,
50 B釋放的同時也會使A的計數減一,同時pa自己析構時也會使資源A的計數減一,那么A的計數為0,A得到釋放。
51 */
52 
53 void main()
54 {
55     fun();
56     system("pause");
57 }

四、unique_ptr

  unique_ptr 是一個獨享所有權的智能指針,它提供了嚴格意義上的所有權。它取代了C++98中的auto_ptr。

用法和auto_ptr類似,詳情見一下代碼:

 1 #include <iostream>
 2 #include <memory>
 3 #include <string>
 4 using namespace std;
 5 
 6 unique_ptr<string> fun2(){
 7     return unique_ptr<string>(new string("RUS"));
 8 }
 9 
10 void fun(){
11     unique_ptr<string> pa(new string("CHN"));
12     //unique_ptr沒有use_count()方法
13     unique_ptr<string> pb(new string("USA"));
14 
15     pb = move(pa);
16     //p2=p1;//錯誤,不能直接用等於號
17     if (pa == nullptr)
18         cout << "pa現在為空" << endl;
19 
20     cout << "*pb " << *pb << endl;//pb變成了“CHA”
21 
22     string* ps = pb.release();//清空當前智能指針所指的資源對象,並返回指針
23     cout << "*ps " << *ps << endl;//ps變成了“CHA”
24 
25     pa.reset(ps);//重置指向另一個對象
26     cout << "*pa " << *pa << endl;//pa變成了“CHA”
27 
28     pb = fun2();//接收函數的返回值可以用等於號,因為使用了移動構造函數
29     cout << "*pb " << *pb << endl;//pb變成了“RUS”
30 }
31 
32 void main()
33 {
34     fun();
35     system("pause");
36 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM