C++11 std::shared_ptr總結與使用


最近看代碼,智能指針用的比較多,自己平時用的少,周末自己總結總結。方便后續使用。

std::shared_ptr大概總結有以下幾點:

(1) 智能指針主要的用途就是方便資源的管理,自動釋放沒有指針引用的資源

(2) 使用引用計數來標識是否有多余指針指向該資源。(注意,shart_ptr本身指針會占1個引用)

(3) 在賦值操作中, 原來資源的引用計數會減一,新指向的資源引用計數會加一。

     std::shared_ptr<Test> p1(new Test);

     std::shared_ptr<Test> p2(new Test);

     p1 = p2;

(4) 引用計數加一/減一操作是原子性的,所以線程安全的。

(5) make_shared要優於使用new,make_shared可以一次將需要內存分配好

std::shared_ptr<Test> p = std::make_shared<Test>();
std::shared_ptr<Test> p(new Test);

(6) std::shared_ptr的大小是原始指針的兩倍,因為它的內部有一個原始指針指向資源,同時有個指針指向引用計數。

(7) 引用計數是分配在動態分配的,std::shared_ptr支持拷貝,新的指針獲可以獲取前引用計數個數。

 

下面是一段示例代碼,注釋詳細:

 1 include <iostream>
 2 #include <memory>
 3 #include <thread>
 4 #include <chrono>
 5 #include <mutex>
 6 
 7 struct Test
 8 {
 9     Test() { std::cout << "  Test::Test()\n"; }
10     ~Test() { std::cout << "  Test::~Test()\n"; }
11 };
12 
13 //線程函數
14 void thr(std::shared_ptr<Test> p)
15 {
16     //線程暫停1s
17     std::this_thread::sleep_for(std::chrono::seconds(1));
18 
19     //賦值操作, shared_ptr引用計數use_cont加1(c++11中是原子操作)
20     std::shared_ptr<Test> lp = p;
21     {   
22         //static變量(單例模式),多線程同步用
23         static std::mutex io_mutex;
24 
25         //std::lock_guard加鎖
26         std::lock_guard<std::mutex> lk(io_mutex);
27         std::cout << "local pointer in a thread:\n"
28                   << "  lp.get() = " << lp.get()
29                   << ", lp.use_count() = " << lp.use_count() << '\n';
30     }   
31 }
32 
33 int main()
34 {
35     //使用make_shared一次分配好需要內存
36     std::shared_ptr<Test> p = std::make_shared<Test>();
37     //std::shared_ptr<Test> p(new Test);
38  
39     std::cout << "Created a shared Test\n"
40               << "  p.get() = " << p.get()
41               << ", p.use_count() = " << p.use_count() << '\n';
42 
43     //創建三個線程,t1,t2,t3
44     //形參作為拷貝, 引用計數也會加1
45     std::thread t1(thr, p), t2(thr, p), t3(thr, p);
46     std::cout << "Shared ownership between 3 threads and released\n"
47               << "ownership from main:\n"
48               << "  p.get() = " << p.get()
49               << ", p.use_count() = " << p.use_count() << '\n';
50     //等待結束
51     t1.join(); t2.join(); t3.join();
52     std::cout << "All threads completed, the last one deleted\n";
53 
54     return 0;
55 }

編譯執行:

 

參考:

http://www.cnblogs.com/xudong-bupt/p/6736783.html

https://blog.csdn.net/coolmeme/article/details/43195587

http://www.cnblogs.com/lanxuezaipiao/p/4132096.html


免責聲明!

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



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