循環參考:
引用計數是一種便利的記憶體管理機制,但它有一個很大的缺點,那就是不能管理循環參考的對象。一個簡單的例子如下:
#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++中那臭名昭著的記憶體流失。
一般來講,解除這種循環參考有下面有三種可行的方法:
- 當只剩下最後一個引用的時候需要手動打破循環參考釋放對象。
- 當parent的生存期超過children的生存期的時候,children改為使用一個普通指標指向parent。
- 使用弱引用的智能指標打破這種循環參考。
雖然這三種方法都可行,但方法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++來說,由於沒有記憶體回收機制,記憶體流失對每一個程式員來說都是一個非常頭痛的問題。