C++ 11 智慧指標的坑和引用計數的意義
一、本節內容
本節內容包括:
- 對標準庫的擴充: 智慧指標和引用計數
- RAII 與引用計數
std::shared_ptr
std::unique_ptr
std::weak_ptr
二、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
指標。例如:
- voidfoo(std::shared_ptr
- {
- (*i)++;
- }
- intmain()
- {
- // auto pointer = new int(10); // 非法, 不允許直接賦值
- // 構造了一個 std::shared_ptr
- auto pointer = std::make_shared<int>(10);
- foo(pointer);
- std::cout << *pointer << std::endl; // 11
- // 離開作用域前,shared_ptr 會被析構,從而釋放記憶體
- return 0;
- }
std::shared_ptr
可以通過 get()
方法來獲取原始指標,通過 reset()
來減少一個引用計數,並通過get_count()
來檢視一個物件的引用計數。例如:
- auto pointer = std::make_shared<int>(10);
- auto pointer2 = pointer; // 引用計數+1
- auto pointer3 = pointer; // 引用計數+1
- int *p = pointer.get(); // 這樣不會增加引用計數
- std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 3
- std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 3
- std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 3
- pointer2.reset();
- std::cout << "reset pointer2:" << std::endl;
- std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 2
- std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0, pointer2 已 reset
- std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 2
- pointer3.reset();
- std::cout << "reset pointer3:" << std::endl;
- std::cout << "pointer.use_count() = " << pointer.use_count() << std::endl; // 1
- std::cout << "pointer2.use_count() = " << pointer2.use_count() << std::endl; // 0
- std::cout << "pointer3.use_count() = " << pointer3.use_count() << std::endl; // 0, pointer3 已 reset
四、std::unique_ptr
std::unique_ptr
是一種獨佔的智慧指標,它禁止其他智慧指標與其共享同一個物件,從而保證了程式碼的安全:
- std::unique_ptr<int> pointer = std::make_unique<int>(10); // make_unique 從 C++14 引入
- std::unique_ptr<int> pointer2 = pointer; // 非法
make_unique 並不複雜,C++11 沒有提供 std::make_unique,可以自行實現:
- template<typename T, typename ...Args>
- std::unique_ptr<T> make_unique( Args&& ...args ) {
- return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) );
- }
至於為什麼沒有提供,C++ 標準委員會主席 Herb Sutter 在他的部落格中提到原因是因為『被他們忘記了』。
既然是獨佔,換句話說就是不可複製。但是,我們可以利用 std::move
將其轉移給其他的 unique_ptr
,例如:
- struct Foo {
- Foo() { std::cout << "Foo::Foo" << std::endl; }
- ~Foo() { std::cout << "Foo::~Foo" << std::endl; }
- voidfoo(){ std::cout << "Foo::foo" << std::endl; }
- };
- voidf(const Foo &){
- std::cout << "f(const Foo&)" << std::endl;
- }
- intmain(){
- std::unique_ptr<Foo> p1(std::make_unique<Foo>());
- // p1 不空, 輸出
- if (p1) p1->foo();
- {
- std::unique_ptr<Foo> p2(std::move(p1));
- // p2 不空, 輸出
- f(*p2);
- // p2 不空, 輸出
- if(p2) p2->foo();
- // p1 為空, 無輸出
- if(p1) p1->foo();
- p1 = std::move(p2);
- // p2 為空, 無輸出
- if(p2) p2->foo();
- std::cout << "p2 被銷燬" << std::endl;
- }
- // p1 不空, 輸出
- if (p1) p1->foo();
- // Foo 的例項會在離開作用域時被銷燬
- }
五、std::weak_ptr
如果你仔細思考 std::shared_ptr
就會發現依然存在著資源無法釋放的問題。看下面這個例子:
- class A;
- class B;
- class A {
- public:
- std::shared_ptr<B> pointer;
- ~A() {
- std::cout << "A 被銷燬" << std::endl;
- }
- };
- class B {
- public:
- std::shared_ptr<A> pointer;
- ~B() {
- std::cout << "B 被銷燬" << std::endl;
- }
- };
- intmain(){
- std::shared_ptr<A> a = std::make_shared<A>();
- std::shared_ptr<B> b = std::make_shared<B>();
- a->pointer = b;
- b->pointer = a;
- return 0;
- }
執行結果是 A, B 都不會被銷燬,這是因為 a,b 內部的 pointer 同時又引用了 a,b
,這使得 a,b
的引用計數均變為了 2,而離開作用域時,a,b
智慧指標被析構,卻智慧造成這塊區域的引用計數減一,這樣就導致了 a,b
物件指向的記憶體區域引用計數不為零,而外部已經沒有辦法找到這塊區域了,也就造成了記憶體洩露,如圖所示:
解決這個問題的辦法就是使用弱引用指標 std::weak_ptr
,std::weak_ptr
是一種弱引用(相比較而言 std::shared_ptr
就是一種強引用)。弱引用不會引起引用計數增加,當換用弱引用時候,最終的釋放流程如下圖所示:
在上圖中,最後一步只剩下 B,而 B 並沒有任何智慧指標引用它,因此這塊記憶體資源也會被釋放。
std::weak_ptr
沒有 *
運算子和 ->
運算子,所以不能夠對資源進行操作,它的唯一作用就是用於檢查 std::shared_ptr
是否存在,expired()
方法在資源未被釋放時,會返回 true
,否則返回 false
。
正確的程式碼如下: