歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C++智能指針循環引用解決

C++智能指針循環引用解決

日期:2017/3/1 10:00:39   编辑:Linux編程

前言: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對象已被釋放。

Copyright © Linux教程網 All Rights Reserved