boost::shared_ptr与std::tr1::shared_ptr

从命名空间可以看出一个是boost的,另一个是tr1的,当然tr1也是从boost中移植过来的,在Windows中需要安装vs2008+sp1补丁才能支持。
智能指针,它们功能一样,都有引用计数的功能,即智能指针被拷贝后会增加引用计数,这样就不用担心之前的智能指针销毁资源而导致拷贝后的智能指针不能用。
// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <boost/shared_ptr.hpp>
#include <memory>

struct Widget;
typedef boost::shared_ptr<Widget> WidgetPtr;
typedef std::tr1::shared_ptr<Widget> WidgetTr1Ptr;

struct Widget
{
	Widget()
	{
		std::cout << "Widget" << std::endl;
	}

	~Widget()
	{
		std::cout << "~Widget" << std::endl;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	{
		WidgetPtr p1(new Widget());
		WidgetTr1Ptr p2(new Widget());
	}

	system("pause");
	return 0;
}

#include <iostream>
#include <boost/shared_ptr.hpp>
#include <string>

class Widget
{
public:
	typedef boost::shared_ptr<Widget> pointer;

public:
	~Widget()
	{
		std::cout << "this is destory: " << i_ << std::endl;
	}

	static pointer create(int i)
	{
		return pointer(new Widget(i));
	}

	void test()
	{
		std::cout << "this is test: " << i_ << std::endl;
	}

private:
	explicit Widget(int i)
		: i_(i)
	{
		std::cout << "this is create: " << i_ << std::endl;
	}

private:
	int i_;
};

int main(void)
{
	{
		Widget::pointer p = Widget::create(1);
		p = Widget::create(2);
		p = Widget::create(3);
	}

	const char sep[] = ";";

	std::string name = "proxy";
	std::string out = name + sep;
	std::cout << out << std::endl;

	system("pause");
	return 0;
}

// 当p指向另外一个智能指针对象时,之前p所指向的对象会自动析构

//输出结果:
// this is create: 1
// this is create: 2
// this is destory: 1
// this is create: 3
// this is destory: 2
// this is destory: 3


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值