您的位置:首页 > 其它

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

2015-01-06 17:47 295 查看
#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: