成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

一文掌握 C++ 智能指針的使用

開發 后端
C++11 引入了智能指針的概念,使用了引用計數的想法,讓程序員不再需要關心手動釋放內存。

[[422939]]

 RAII 與引用計數

了解 Objective-C/Swift 的程序員應該知道引用計數的概念。引用計數這種計數是為了防止內存泄露而產生的。

基本想法是對于動態分配的對象,進行引用計數,每當增加一次對同一個對象的引用,那么引用對象的引用計數就會增加一次, 每刪除一次引用,引用計數就會減一,當一個對象的引用計數減為零時,就自動刪除指向的堆內存。

在傳統C++中,『記得』手動釋放資源,總不是最佳實踐。因為我們很有可能就忘記了去釋放資源而導致泄露。所以通常的做法是對于一個對象而言,我們在構造函數的時候申請空間,而在析構函數(在離開作用域時調用)的時候釋放空間, 也就是我們常說的 RAII 資源獲取即初始化技術。

凡事都有例外,我們總會有需要將對象在自由存儲上分配的需求,在傳統 C++ 里我們只好使用 new 和 delete 去 『記得』對資源進行釋放。而 C++11 引入了智能指針的概念,使用了引用計數的想法,讓程序員不再需要關心手動釋放內存。

這些智能指針就包括 std::shared_ptr std::unique_ptr std::weak_ptr,使用它們需要包含頭文件<memory>。

注意:引用計數不是垃圾回收,引用計數能夠盡快收回不再被使用的對象,同時在回收的過程中也不會造成長時間的等待, 更能夠清晰明確的表明資源的生命周期。

std::shared_ptr

std::shared_ptr 是一種智能指針,它能夠記錄多少個 shared_ptr 共同指向一個對象,從而消除顯式的調用 delete,當引用計數變為零的時候就會將對象自動刪除。

但還不夠,因為使用 std::shared_ptr 仍然需要使用 new 來調用,這使得代碼出現了某種程度上的不對稱。

std::make_shared 就能夠用來消除顯式的使用 new,所以 std::make_shared 會分配創建傳入參數中的對象, 并返回這個對象類型的 std::shared_ptr 指針。例如: 

  1. #include <iostream>  
  2. #include <memory>  
  3. void foo(std::shared_ptr<int> i)  
  4.  
  5.     (*i)++;  
  6.  
  7. int main()  
  8.  
  9.     // auto pointer = new int(10); // illegal, no direct assignment  
  10.     // Constructed a std::shared_ptr  
  11.     auto pointer = std::make_shared<int>(10);  
  12.     foo(pointer);  
  13.     std::cout << *pointer << std::endl; // 11  
  14.     // The shared_ptr will be destructed before leaving the scope  
  15.     return 0;  

std::shared_ptr 可以通過 get() 方法來獲取原始指針,通過 reset() 來減少一個引用計數, 并通過 use_count() 來查看一個對象的引用計數。例如: 

  1. auto pointer = std::make_shared<int>(10);  
  2. auto pointerpointer2 = pointer; // 引用計數+1  
  3. auto pointerpointer3 = pointer; // 引用計數+1  
  4. int *p = pointer.get(); // 這樣不會增加引用計數  
  5. std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 3  
  6. std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 3  
  7. std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 3  
  8. pointer2.reset();  
  9. std::cout << "reset pointer2:" << std::endl 
  10. std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 2  
  11. std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0, pointer2 已 reset  
  12. std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 2  
  13. pointer3.reset();  
  14. std::cout << "reset pointer3:" << std::endl 
  15. std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 1  
  16. std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0  
  17. std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 0, pointer3 已 reset 

std::unique_ptr

std::unique_ptr 是一種獨占的智能指針,它禁止其他智能指針與其共享同一個對象,從而保證代碼的安全: 

  1. std::unique_ptr<int> pointer = std::make_unique<int>(10); // make_unique 從 C++14 引入  
  2. std::unique_ptr<int> pointerpointer2 = pointer; // 非法 

make_unique 并不復雜,C++11 沒有提供 std::make_unique,可以自行實現: 

  1. template<typename T, typename ...Args>  
  2. std::unique_ptr<T> make_unique( Args&& ...args ) {  
  3.   return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );  

至于為什么沒有提供,C++ 標準委員會主席 Herb Sutter 在他的博客中提到原因是因為『被他們忘記了』。

既然是獨占,換句話說就是不可復制。但是,我們可以利用 std::move 將其轉移給其他的 unique_ptr,例如: 

  1. #include <iostream>  
  2. #include <memory>  
  3. struct Foo {  
  4.     Foo() { std::cout << "Foo::Foo" << std::endl; }  
  5.     ~Foo() { std::cout << "Foo::~Foo" << std::endl; }  
  6.     void foo() { std::cout << "Foo::foo" << std::endl; }  
  7. };  
  8. void f(const Foo &) {  
  9.     std::cout << "f(const Foo&)" << std::endl 
  10.  
  11. int main() {  
  12.     std::unique_ptr<Foo> p1(std::make_unique<Foo>());  
  13.     // p1 不空, 輸出  
  14.     if (p1) p1->foo();  
  15.     {  
  16.         std::unique_ptr<Foo> p2(std::move(p1));  
  17.         // p2 不空, 輸出  
  18.         f(*p2);  
  19.         // p2 不空, 輸出  
  20.         if(p2) p2->foo();  
  21.         // p1 為空, 無輸出  
  22.         if(p1) p1->foo();  
  23.         p1 = std::move(p2);  
  24.         // p2 為空, 無輸出  
  25.         if(p2) p2->foo();  
  26.         std::cout << "p2 被銷毀" << std::endl 
  27.     }  
  28.     // p1 不空, 輸出  
  29.     if (p1) p1->foo();  
  30.     // Foo 的實例會在離開作用域時被銷毀  

std::weak_ptr

如果你仔細思考 std::shared_ptr 就會發現依然存在著資源無法釋放的問題??聪旅孢@個例子: 

  1. struct A;  
  2. struct B;  
  3. struct A {  
  4.     std::shared_ptr<B> pointer;  
  5.     ~A() {  
  6.         std::cout << "A 被銷毀" << std::endl 
  7.     }  
  8. };  
  9. struct B {  
  10.     std::shared_ptr<A> pointer;  
  11.     ~B() {  
  12.         std::cout << "B 被銷毀" << std::endl 
  13.     }  
  14. };  
  15. int main() {  
  16.     auto a = std::make_shared<A>();  
  17.     auto b = std::make_shared<B>();  
  18.     a->pointer = b 
  19.     b->pointer = a 

運行結果是 A, B 都不會被銷毀,這是因為 a,b 內部的 pointer 同時又引用了 a,b,這使得 a,b 的引用計數均變為了 2,而離開作用域時,a,b 智能指針被析構,卻只能造成這塊區域的引用計數減一。

這樣就導致了 a,b 對象指向的內存區域引用計數不為零,而外部已經沒有辦法找到這塊區域了,也就造成了內存泄露,如圖 1:

圖 1

解決這個問題的辦法就是使用弱引用指針 std::weak_ptr,std::weak_ptr是一種弱引用(相比較而言 std::shared_ptr 就是一種強引用)。

弱引用不會引起引用計數增加,當換用弱引用時候,最終的釋放流程如圖 2 所示:

圖 2

在上圖中,最后一步只剩下 B,而 B 并沒有任何智能指針引用它,因此這塊內存資源也會被釋放。

std::weak_ptr 沒有 * 運算符和 -> 運算符,所以不能夠對資源進行操作,它的唯一作用就是用于檢查 std::shared_ptr 是否存在,其 expired() 方法能在資源未被釋放時,會返回 false,否則返回 true。

總結

智能指針這種技術并不新奇,在很多語言中都是一種常見的技術,現代 C++ 將這項技術引進,在一定程度上消除了 new/delete 的濫用,是一種更加成熟的編程范式。 

 

責任編輯:龐桂玉 來源: C語言與C++編程
相關推薦

2010-12-17 10:07:59

2010-02-05 14:36:20

C++智能指針

2023-11-17 11:48:08

智能指針C++

2024-12-26 10:45:08

2023-12-20 12:40:51

C++RAII編程

2024-04-28 08:14:29

C#隊列Queue

2024-05-30 08:05:17

2010-01-28 13:57:19

C++指針基礎

2024-02-01 11:57:31

this指針代碼C++

2022-12-20 07:39:46

2023-12-21 17:11:21

Containerd管理工具命令行

2022-10-21 17:24:34

契約測試定位

2024-01-24 11:44:44

C++智能指針開發

2021-05-12 18:22:36

Linux 內存管理

2023-07-04 08:56:07

指針類型Golang

2010-01-27 14:18:41

Android智能指針

2023-12-29 15:30:41

內存存儲

2015-07-27 11:34:03

Linux內核指針

2024-11-19 09:00:00

Pythondatetime模塊

2025-04-18 05:50:59

Spring接口Aware
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 亚洲高清在线 | 日韩成人一区二区 | 午夜影院视频 | 色www精品视频在线观看 | 91视频国产一区 | 国产一区二区久久 | 国产成人99久久亚洲综合精品 | 午夜精品一区二区三区免费视频 | 国产精品久久免费观看 | 正在播放亚洲 | 九九九久久国产免费 | 黄色片在线观看网址 | 中文字幕亚洲视频 | sese视频在线观看 | 欧美一区二区在线观看 | 日本色高清 | 国产在线中文字幕 | 麻豆精品国产91久久久久久 | 色综合天天天天做夜夜夜夜做 | 国产精品一区在线观看你懂的 | 久久久精品一区 | 在线日韩 | 日韩在线电影 | 亚洲国产一区二区三区四区 | 国产日韩一区 | 成人亚洲精品久久久久软件 | 久久久精品一区二区三区 | 春色av | 国产精品99久久久久久动医院 | 国产日韩精品一区 | 91文字幕巨乱亚洲香蕉 | 日韩av在线一区二区三区 | 在线观看亚洲一区二区 | 一区二区三区精品 | 亚洲激情网站 | 国产91精品久久久久久久网曝门 | 日韩综合在线播放 | 国产激情视频网 | 大香在线伊779 | 国产一区二区在线观看视频 | 色男人的天堂 |