Boost智能指針——weak_ptr

循環引用:

引用計數是一種便利的內存管理機制,但它有一個很大的缺點,那就是不能管理循環引用的對象。一個簡單的例子如下:

#include<string>
#include<iostream>
#include<boost/shared_ptr.hpp>
#include<boost/weak_ptr.hpp>

class parent;
class children;

typedef boost::shared_ptr<parent> parent_ptr;
typedef boost::shared_ptr<children> children_ptr;

class parent
{
public:
   ~parent() { std::cout <<"destroying parent\n"; }

public:
   children_ptr children;
};

class children
{
public:
   ~children() { std::cout <<"destroying children\n"; }

public:
   parent_ptr parent;
};


void test()
{
   parent_ptr father(new parent());
   children_ptr son(new children);

   father->children = son;
   son->parent = father;
}

void main()
{
   std::cout<<"begin test...\n";
   test();
   std::cout<<"end test.\n";
}

運行該程序可以看到,即使退出了test函數後,由於parent和children對象互相引用,它們的引用計數都是1,不能自動釋放,並且此時這兩個對象再無法訪問到。這就引起了c++中那臭名昭著的內存泄漏

一般來講,解除這種循環引用有下面有三種可行的方法:

  1. 當只剩下最後一個引用的時候需要手動打破循環引用釋放對象。
  2. 當parent的生存期超過children的生存期的時候,children改爲使用一個普通指針指向parent。
  3. 使用弱引用的智能指針打破這種循環引用。

雖然這三種方法都可行,但方法1和方法2都需要程序員手動控制,麻煩且容易出錯。這裏主要介紹一下第三種方法和boost中的弱引用的智能指針boost::weak_ptr。

強引用和弱引用

一個強引用當被引用的對象活着的話,這個引用也存在(就是說,當至少有一個強引用,那麼這個對象就不能被釋放)。boost::share_ptr就是強引用。

相對而言,弱引用當引用的對象活着的時候不一定存在。僅僅是當它存在的時候的一個引用。弱引用並不修改該對象的引用計數,這意味這弱引用它並不對對象的內存進行管理,在功能上類似於普通指針,然而一個比較大的區別是,弱引用能檢測到所管理的對象是否已經被釋放,從而避免訪問非法內存。

boost::weak_ptr

boost::weak_ptr<T>是boost提供的一個弱引用的智能指針,它的聲明可以簡化如下:

namespace boost {

template<typename T> class weak_ptr {
public:
template <typename Y>
       weak_ptr(const shared_ptr<Y>& r);

       weak_ptr(const weak_ptr& r);

       ~weak_ptr();

       T* get() const;
bool expired() const;
       shared_ptr<T> lock() const;
   };
}

可以看到,boost::weak_ptr必須從一個boost::share_ptr或另一個boost::weak_ptr轉換而來,這也說明,進行該對象的內存管理的是那個強引用的boost::share_ptr。boost::weak_ptr只是提供了對管理對象的一個訪問手段。

boost::weak_ptr除了對所管理對象的基本訪問功能(通過get()函數)外,還有兩個常用的功能函數:expired()用於檢測所管理的對象是否已經釋放;lock()用於獲取所管理的對象的強引用指針。

通過boost::weak_ptr來打破循環引用

由於弱引用不更改引用計數,類似普通指針,只要把循環引用的一方使用弱引用,即可解除循環引用。對於上面的那個例子來說,只要把children的定義改爲如下方式,即可解除循環引用:

class children
{
public:
   ~children() { std::cout <<"destroying children\n"; }

public:
   boost::weak_ptr<parent> parent;
};

最後值得一提的是,雖然通過弱引用指針可以有效的解除循環引用,但這種方式必須在程序員能預見會出現循環引用的情況下才能使用,也可以是說這個僅僅是一種編譯期的解決方案,如果程序在運行過程中出現了循環引用,還是會造成內存泄漏的。因此,不要認爲只要使用了智能指針便能杜絕內存泄漏。畢竟,對於C++來說,由於沒有垃圾回收機制,內存泄漏對每一個程序員來說都是一個非常頭痛的問題。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章