boost:智能指针

简介:

 

智能指针是一种具备指针类似行为的对象,当不在需要它的时候自动删除其引用的c++对象。直接点说就是自动析构C++对象。

boost提供了6种智能指针,如下所示:

scoped_ptr<boost/scoped_ptr.hpp>单个对象的简单的唯一所有权. 不能拷贝.
scoped_array<boost/scoped_array.hpp>数组对象的唯一所有权. 不能拷贝.
shared_ptr<boost/shared_ptr.hpp>多个指针间共享对象所有权.
shared_array<boost/shared_array.hpp>多个指针间共享数组所有权
weak_ptr<boost/weak_ptr.hpp>

访问被shared_ptr所有的对象,但并不拥有这个对象。通常与shared_prt

联合使用来避免环形引用

intrusive_ptr<boost/intrusive_ptr.hpp>

共享有着嵌入了引用计数对象的所有权。它在性能上比shared_ptr更好,

但需要对象类型实现自己的引用计数机制

 

基本用法:


1、scoped ptr

就跟它的名字一样,局部作用域指针对象,控制局部对象的自动删除。

使用delete删除对象使用scoped_ptr
void manual_del()
{
  test* p(new test);

  if (!p->prepared() )
  
  {
    delete p;
    return;
  }

  p->do_some_thing();
  delete p;
}
#include "boost/smart_ptr.h"

void auto_del()
{
  boost::scoped_ptr<test> 
            sp(new test);

  if (!sp->prepared() )
  
    return; 

  sp->do_some_thing();

}

示例:

 

#include <iostream>
#include <boost/smart_ptr/scoped_ptr.hpp>
#include <boost/smart_ptr/scoped_array.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/format.hpp>

using namespace std;
using namespace boost;

class scoped_ptr_test_class
{
public:
	scoped_ptr_test_class()
	{
		cout<<boost::format("object constructed. address: %1%")%int((int*)this)<<endl;
	}
	~scoped_ptr_test_class()
	{
		cout<<boost::format("object destructed. address: %1%")%int((int*)this)<<endl;
	}
};
void scoped_ptr_test()
{
	cout<<"******************scopted_ptr_test**************"<<endl;	
	scoped_ptr_test_class *obj = new scoped_ptr_test_class;

	{
		scoped_ptr<scoped_ptr_test_class> sp(obj);
	}
	//scoped_ptr在删除引用对象时,并不会将其引用指针置0
	//参照其构造函数: explicit scoped_ptr( T * p = 0 ): px( p ) 
	BOOST_TEST(obj != 0);
	cout<<"****************scopted_ptr_array_test************"<<endl;
	scoped_ptr_test_class* obj_array = new scoped_ptr_test_class[2];
	scoped_array<scoped_ptr_test_class> sar(obj_array);	
}
int main()
{	
	scoped_ptr_test();
	return 0;
}


 

 

2、shared ptr

共享指针能对其其所属对象的引用计数进行管理,这在一处生成多处使用的场合下特别有用,因为你不用四处查看代码确保没有多次delete那些对象。

与scoped_ptr不同,shared_ptr可以和标准库的容器一起使用,并且可以安全的应用在多线程环境中。

示例:

 

#include <iostream>
#include <boost/smart_ptr.hpp>
#include <boost/format.hpp>
#include <boost/detail/lightweight_test.hpp>

using namespace std;
using namespace boost;

class shared_ptr_test_class
{
public:
	shared_ptr_test_class()
	{
		cout<<boost::format("object constructed. address: %1%")%int((int*)this)<<endl;
	}
	~shared_ptr_test_class()
	{
		cout<<boost::format("object destructed. address: %1%")%int((int*)this)<<endl;
	}
	void print()
	{
		cout<<boost::format("object still exist:%1%")%int((int*)this)<<endl;
	}
};
typedef boost::shared_ptr<shared_ptr_test_class> test_ptr;
typedef vector<test_ptr> test_vector;
//基本功能测试
void shared_ptr_test()
{
	cout<<"******************basic_test**************"<<endl;	
	shared_ptr_test_class *obj = new shared_ptr_test_class;
	test_ptr sp1(obj);

	{
		//注意,此处不能使用下面的方式初始化一个共享指针,会多次析构对象
		//boost::shared_ptr<shared_ptr_test_class> sp2(obj);//error
		test_ptr sp2(sp1);
		BOOST_TEST( (sp1.use_count() == sp2.use_count() ) && sp1.use_count() ==2 ) ;
	}

	BOOST_TEST( sp1.use_count() == 1);
	sp1.reset();
	BOOST_TEST(sp1.use_count() ==0);	
}

//容器测试
void vector_test_fun()
{
	cout<<"******************container_test**************"<<endl;	
	test_vector vec;
	const int obj_num =2;
	for(int i =0; i<obj_num; i++)
	{
		vec.push_back(test_ptr(new shared_ptr_test_class));
	}
	test_ptr ps[obj_num];
	
	for(int i=0; i<obj_num; i++)
	{
		BOOST_TEST(vec[i].use_count() == 1);
		ps[i] = vec[i];
		BOOST_TEST(vec[i].use_count() == 2);
	}
	vec.clear();

	//对象仍然存在
	for(int i=0; i<obj_num; i++)
	{
		BOOST_TEST(ps[i].use_count() == 1);
		ps[i].get()->print();
	}	
}

int main()
{	
	shared_ptr_test();
	vector_test_fun();
	return 0;
}


 

 

3、intrusive ptr

与intrusive智能指针一起使用的类型或者其父类必须定义两个函数

intrusive_ptr_add_ref

intrusive_ptr_release

示例:

 

#include <iostream>
#include <boost/smart_ptr.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/format.hpp>

using std::cout;
using std::endl;

class test_class_base
{
public:
	virtual ~test_class_base(){}
protected:
	test_class_base():_ref(0)
	{
	}
	int _ref;
private:
	friend void intrusive_ptr_add_ref(test_class_base* p);
	friend void intrusive_ptr_release(test_class_base* p);
};

void intrusive_ptr_add_ref(test_class_base* p)
{
	++(p->_ref);	
}
void intrusive_ptr_release(test_class_base* p)
{
	if(--(p->_ref) ==0)
		delete p;
}

class intrusive_ptr_test_class : public test_class_base
{
public:
	intrusive_ptr_test_class()
	{
		cout<<boost::format("object constructed. address: %1%")%int((int*)this)<<endl;
	}
	~intrusive_ptr_test_class()
	{
		cout<<boost::format("object destructed. address: %1%")%int((int*)this)<<endl;
	}
};
void intrusive_ptr_test()
{
	intrusive_ptr_test_class *obj = new intrusive_ptr_test_class;

	{
		boost::intrusive_ptr<intrusive_ptr_test_class> sp(obj);
	}
}

int main()
{	
	intrusive_ptr_test();
	return 0;
}


 

使用weak_ptr解决循环引用

来看下面的代码

 

#include <boost/smart_ptr.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/format.hpp>

class left;
class right;

typedef boost::shared_ptr<left> left_ptr;
typedef boost::shared_ptr<right> right_ptr;

using std::cout;
using std::endl;

class node
{
public:
	node()
	{
		cout<<boost::format("object constructed. address: %1%")%int((int*)this)<<endl;
	}
	virtual ~node()
	{
		cout<<boost::format("object destructed. address: %1%")%int((int*)this)<<endl;
	}
};
class left : public node
{
public:
	right_ptr _child;
};
class right : public node
{
public:
	left_ptr _parent;
};

void test()
{
	left_ptr left(new left);
	right_ptr right(new right);

	left.get()->_child = right;
	right.get()->_parent = left;

	BOOST_TEST(left.use_count() == 2);
	BOOST_TEST(right.use_count() == 2);
	left.reset();
	//经过一次reset后,这里的实际的引用计数却是0
	//BOOST_TEST(left.use_count() == 1);//会出错
	BOOST_TEST(left.use_count() ==0);
	right.reset();
	BOOST_TEST(right.use_count() ==0);
        //虽然引用计数都为0,但创建的对象都没有析构
}
int main()
{	
	test();
	return 0;
}


 

可以使用weak_ptr来解决此问题

 

 

#include <boost/smart_ptr.hpp>
#include <boost/detail/lightweight_test.hpp>
#include <boost/format.hpp>

class left;
class right;

typedef boost::shared_ptr<left> left_shared_ptr;
typedef boost::shared_ptr<right> right_shared_ptr;

typedef boost::weak_ptr<left> left_weak_ptr;
typedef boost::weak_ptr<right> right_weak_ptr;

using std::cout;
using std::endl;

class node
{
public:
	node()
	{
		cout<<boost::format("object constructed. address: %1%")%int((int*)this)<<endl;
	}
	virtual ~node()
	{
		cout<<boost::format("object destructed. address: %1%")%int((int*)this)<<endl;
	}
};
class left : public node
{
public:
	right_weak_ptr _child;
	void print()
	{
		cout<<"left object"<<endl;
	}
};
class right : public node
{
public:
	left_weak_ptr _parent;
	void other_print()
	{
		
		{
			//该作用域结束后lp自动析构
			left_shared_ptr lp = _parent.lock();
			if(lp)
				lp.get()->print();
		}
	}
};

void test()
{
	left_shared_ptr left(new left);
	right_shared_ptr right(new right);

	left.get()->_child = right;
	right.get()->_parent = left;

	BOOST_TEST(left.use_count() == 1);
	BOOST_TEST(right.use_count() == 1);
	
	left.reset();
	//left 对象析构
	right.reset();
	//right 对象析构
}
int main()
{	
	test();
	return 0;
}


 

 

(boost库目前的最新版本为1.48,关于智能指针的官方资料可以通过链接查看)

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值