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

Lara ·
更新时间:2024-09-20
· 830 次阅读

  前言:C++中智能指针的引入,使得开发人员在与内存的斗争中占据上峰。然而凡事都不会尽善尽美,智能指针的循环引用缺陷还是会引发令人谈虎色变的内存泄露。本文的内容是讲述,如何解决循环引用带来的内存问题。

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

  循环引用示例

#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对象已被释放。



c+ 循环 智能指针 C++ 循环引用 指针

需要 登录 后方可回复, 如果你还没有账号请 注册新账号