C++中智能指针的引入,使得开发人员在与内存的斗争中占据上峰。然而凡事都不会尽善尽美,智能指针的循环引用缺陷还是会引发令人谈虎色变的内存泄露。本文的内容就是讲述,如何解决循环引用带来的内存问题。
背景:智能指针采用Boost库,语言C++,开发工具VS2005,示例程序为Win32程序。
关于Boost库的使用,可见另一篇文章http://blog.csdn.net/segen_jaa/article/details/7407404。
循环引用示例
#include "stdafx.h"
#include
#include
#include
#include
using namespace std;
using namespace boost;
class CCycleRef
{
public:
~CCycleRef()
{
cout <<"destroying CCycleRef"<
}
public:
shared_ptr selfRef;
};
void CycleRefTest()
{
shared_ptr cyclRef(new CCycleRef());
cyclRef->selfRef = cyclRef;
cout<<"reference count:"<
}
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"<
}
public:
weak_ptr selfRef;
};
运行结果
reference count:1
destroying CCycleRef
创建的CCycleRef对象已被释放。