C++智能指针循环引用解决

2012-11-01 15:45:39 · 作者: · 浏览: 410
  C++(www.cppentry.com)中智能指针的引入,使得开发人员在与内存的斗争中占据上峰。然而凡事都不会尽善尽美,智能指针的循环引用缺陷还是会引发令人谈虎色变的内存泄露。本文的内容就是讲述,如何解决循环引用带来的内存问题。

  背景:智能指针采用Boost库,语言C++(www.cppentry.com),开发工具VS2005,示例程序为Win32程序。

  关于Boost库的使用,可见另一篇文章http://blog.csdn.net/segen_jaa/article/details/7407404。

  循环引用示例

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

using namespace std;
using namespace boost;

class CCycleRef
{
public:
    ~CCycleRef()
    {
        cout <<"destroying CCycleRef"<<endl;
    }

public:
    shared_ptr<CCycleRef> selfRef;
};

void CycleRefTest()
{
    shared_ptr<CCycleRef> cyclRef(new CCycleRef());
    cyclRef->selfRef = cyclRef;

    cout<<"reference count:"<<cyclRef.use_count()<<endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
    CycleRefTest();
   
    return 0;
}

  运行结果:

  reference count:2

  创建的CCycleRef对象没有释放掉。

  原因是CCycleRef类进行了自引用,引用计数增加所致,类图如下。

  循环引用解决

  引入weak_ptr弱引用指针即可解决循环引用问题。weak_ptr不会修改引用计数。

  修改CCycleRef类。

class CCycleRef
{
public:
    ~CCycleRef()
    {
        cout <<"destroying CCycleRef"<<endl;
    }

public:
    weak_ptr<CCycleRef> selfRef;
};

  运行结果

  reference count:1

  destroying CCycleRef

  创建的CCycleRef对象已被释放。