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; }
相关文章推荐
- boost.shared_ptr源码整理和使用说明
- boost::shared_ptr的使用方法
- boost::shared_ptr 智能指针在项目中的使用
- [zz]使用boost::shared_ptr的注意条款
- 使用 boost::shared_ptr 时,善用 make_shared 而非 new operator 去动态分配资源
- boost::shared_ptr的多线程使用陷阱
- boost库的智能指针shared_ptr结合容器vector的使用
- 使用boost::shared_ptr的教训
- 记录以下boost::shared_ptr的一个使用细节
- Boost:使用shared_ptr封装资源句柄
- Boost:使用shared_array和shared_ptr
- boost::shared_ptr使用技巧
- boost::shared_ptr的使用方法
- 智能指针tr1::shared_ptr、boost::shared_ptr使用
- boost shared_ptr的使用方法
- 智能指针tr1::shared_ptr、boost::shared_ptr使用
- 小测试:boost之shared_ptr在容器类std::list中的使用
- [C++] Boost智能指针——boost::shared_ptr(使用及原理分析)
- boost shared_ptr 使用注意点。
- 关于boost中shared_ptr使用方法的一些例子