zl程序教程

您现在的位置是:首页 >  其他

当前栏目

boost库在工作(12)引用计数的智能指针intrusive_ptr

智能 工作 12 指针 引用 计数 Boost ptr
2023-09-14 09:10:43 时间

当我们在维护旧代码时,很多情况是身不由己的,想从头来开发,又需要时间过多,投入成本过多,老板当然不愿意。想继续使用旧的代码,又需要投入过多的维护成本。要想在这种情况下,提高代码的维护性,又减少出错,因而想引入智能指针管理。比如已经存在引用计数的对象时,如果再想使用智能指针shared_ptr来管理,显然达不目标了,那么怎么办呢?就这样放弃智能指针的使用吗?显然不行,有没有更好的方法呢?在boost库里,又提供了一个强大的智能指针intrusive_ptr来实现这样的功能。前面的智能指针shared_ptr是提供自己内部的引用计数,我们想修改它的引用计数方法是很困难的,也实现不了,而智能指针intrusive_ptr考虑到这种情况,很方便实现了。如下面的例子:

// boost_007.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <iostream>
#include <boost/intrusive_ptr.hpp>

//接口引用计数
class IUnknown
{  
	int m_lCountRef;  
public:    
	IUnknown() 
		: m_lCountRef(0) 
	{}      

	virtual ~IUnknown() 
	{}

	unsigned long AddRef(void)
	{
		++m_lCountRef; 
		return m_lCountRef;
	}

	unsigned long Release(void)
	{
		if (--m_lCountRef==0)
		{
			delete this;     
		}

		return m_lCountRef;
	} 
protected:    
	IUnknown& operator=(const IUnknown&) 
	{    
		// 无操作      
		return *this;    
	}  
private:    
	// 禁止复制构造函数    
	IUnknown(const IUnknown&); 
};

//软件开发人员: 蔡军生  2013-02-10
//QQ: 9073204
class com_class : public IUnknown 
{
public:  
	com_class() 
	{    
		std::cout << "com_class::com_class()\n";  
	}  

	com_class(const com_class& other) 
	{    
		std::cout << "com_class(const com_class& other)\n";  
	}  

	~com_class() 
	{    
		std::cout << "com_class::~com_class()\n";  
	}

	//定义两个给intrusive_ptr调用函数
	friend void intrusive_ptr_add_ref(IUnknown* p) 
	{        
		p->AddRef();
	}   

	friend void intrusive_ptr_release(IUnknown* p) 
	{       
		p->Release();
	} 
};

int _tmain(int argc, _TCHAR* argv[])
{
	//测试使用。
	std::cout << "Before start of scope\n";  
	{    
		boost::intrusive_ptr<com_class> p1(new com_class());    
		boost::intrusive_ptr<com_class> p2(p1);  
	}  
	std::cout << "After end of scope \n";

	system("PAUSE");

	return 0;
}

在这个例子里,类 IUnknown 就是一个旧代码已经声明的引用计数,然后在派生类 com_class 里实现对引用计数进行增加或减少,就可以使用智能指针 intrusive_ptr 来管理了。