boost::shared_ptr在类和容器中使用

#include "stdafx.h"
#include <boost/shared_ptr.hpp>
#include <iostream>
#include <string>
#include <vector>

using std::vector;
using std::cout;
using std::endl;
using std::ends;

// 成员全部是内置类型,默认构造函数将其全初始化为0
struct Test
{
	int i;
	double d;
	int* pi;
};
typedef boost::shared_ptr<Test> Test_ptr;

// 成员中含任意非内置类型,默认构造函数将不对内置类型成员初始化
typedef boost::shared_ptr<int> int_ptr;
struct Test2
{
	std::string s;
	int_ptr i_ptr;
	int i;
	double d;
};
typedef boost::shared_ptr<Test2> Test_ptr2;

int _tmain(int argc, _TCHAR* argv[])
{
//	int *p; // 未初始化的指针指向的值是随机的
// 	if(!p) // error,vs2012指示使用了未初始化的局部变量
// 	{
// 		cout<<"p is null"<<endl;
// 	}

	// shared_ptr()的默认构造函数不做任何事
	/* shared_ptr() _NOEXCEPT
	*  {	// construct empty shared_ptr object
	*  }
	*/

/*	Test_ptr ptr(Test_ptr());*/
	Test_ptr ptr; // 等价方式:Test_ptr ptr = Test_ptr();或者 Test_ptr ptr = 0;

	Test_ptr ptr2(new Test()); // Test默认构造函数调用
	// 使用 Test_ptr ptr(Test_ptr());将报错,LNK1120:无法解析的外部符号
	if(!ptr) // ptr==0
	{
		cout<<"ptr is null"<<endl;
	}
	// 使用 Test_ptr ptr(Test_ptr());编译报错ptr不是“类或结构”
	// 使用 Test_ptr ptr = Test_ptr(); 运行时错误:访问未知内存
/*	cout<<ptr->i<<endl; // error! */

	if(!ptr2)
	{
		cout<<"ptr2 is null"<<endl;
	}
	cout<<ptr2->i<<endl; // 0
	cout<<ptr2->d<<endl; // 0
	if(!ptr2->pi) // pi==0
		cout<<"pi is null"<<endl;
	/*cout<<*ptr2->pi<<endl; // error*/

	Test_ptr2 ptr3(new Test2());
	if(!ptr3)
	{
		cout<<"ptr3 is null"<<endl;
	}
	cout<<ptr3->i<<endl; // 随机数
	cout<<ptr3->d<<endl; // 随机数
	if(!ptr3->i_ptr) // i_ptr==0
		cout<<"i_ptr is null"<<endl;
	cout<<ptr3->i_ptr<<endl; // 00000000

	Test_ptr ptr4 = ptr2;
	Test t = *ptr2;
	t.i = 10;
	*ptr4 = t;
	cout<<ptr4->i<<endl; // 改变ptr4而不改变ptr2

	vector<int_ptr> v;
	for(int i=0; i<10; ++i)
	{
		int_ptr p(new int(i));
		v.push_back(p);
	}
	vector<int_ptr> v2 = v;
	*v2[5] = 99; // 一变具变
	int_ptr i_ptr2(new int(30));
	v2.back() = i_ptr2; // 只改变v2;
	*v2.begin() = i_ptr2; // 只改变v2;
	v.clear(); // 只改变v;
	int_ptr i_ptr(new int(50));
	v.push_back(i_ptr); // 只改变v;
	
	vector<int_ptr>::iterator it;
	for(it=v2.begin(); it!=v2.end(); ++it)
		cout<<**it<<ends;                    
	cout<<endl;
	for(it=v.begin(); it!=v.end(); ++it)
		cout<<**it<<ends;
	cout<<endl;

	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值