歡迎您光臨本站 註冊首頁

C++11 std::shared

←手機掃碼閱讀     f2h0b53ohn @ 2020-06-11 , reply:0

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

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

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

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

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

  std::shared_ptrp1(new Test);  std::shared_ptrp2(new Test);  p1 = p2;

 

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

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

  std::shared_ptrp = std::make_shared();  std::shared_ptrp(new Test);

 

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

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

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

  include#include#include#include#includestruct Test  {   Test() { std::cout << " Test::Test() "; }   ~Test() { std::cout << " Test::~Test() "; }  };    //線程函數  void thr(std::shared_ptrp)  {   //線程暫停1s   std::this_thread::sleep_for(std::chrono::seconds(1));     //賦值操作, shared_ptr引用計數use_cont加1(c++11中是原子操作)   std::shared_ptrlp = p;   {   //static變量(單例模式),多線程同步用   static std::mutex io_mutex;     //std::lock_guard加鎖   std::lock_guardlk(io_mutex);   std::cout << "local pointer in a thread: "   << " lp.get() = " << lp.get()   << ", lp.use_count() = " << lp.use_count() << ' ';   }  }    int main()  {   //使用make_shared一次分配好需要內存   std::shared_ptrp = std::make_shared();   //std::shared_ptrp(new Test);     std::cout << "Created a shared Test "   << " p.get() = " << p.get()   << ", p.use_count() = " << p.use_count() << ' ';     //創建三個線程,t1,t2,t3   //形參作為拷貝, 引用計數也會加1   std::thread t1(thr, p), t2(thr, p), t3(thr, p);   std::cout << "Shared ownership between 3 threads and released "   << "ownership from main: "   << " p.get() = " << p.get()   << ", p.use_count() = " << p.use_count() << ' ';   //等待結束   t1.join(); t2.join(); t3.join();   std::cout << "All threads completed, the last one deleted ";     return 0;  }

 

編譯執行:



[f2h0b53ohn ] C++11 std::shared已經有256次圍觀

http://coctec.com/docs/c/language/show-post-237970.html