c++智能指针:boost::scoped_ptr,boost::shared_ptr,boost::scoped_array
2015-12-15 14:42
549 查看
boost::scoped_ptr使用示例:
运行结果:
如果增加赋值语句,则会提示编译错误。
查看源码实现,发现赋值语句声明为private
boost::shared_ptr使用示例:
执行结果:
boost::scoped_array使用示例:
运行结果:
和scoped_ptr类似,赋值运算符被声明为私有。 ->改为用。标识。
[code]#include <iostream> #include <string> #include <boost/smart_ptr.hpp> using namespace std; class TestBody { public: TestBody(int param = 0):m_num(param) { m_info = "INFO"; cout<<"construct TestBody"<<endl; } ~TestBody() { cout<<"destory TestBody"<<endl; } void SetInfo(string info) { m_info = info; } void PrintInfo() { cout<<"info:"<<m_info<<endl; } private: int m_num; string m_info; }; void TestBoostScopedPtr() { boost::scoped_ptr<TestBody> smartPoint1(new TestBody(1)); if(smartPoint1.get()) { smartPoint1->PrintInfo(); smartPoint1->SetInfo("TestBoostScopedPtr"); smartPoint1->PrintInfo(); } } int main(void) { TestBoostScopedPtr(); return 0; }
运行结果:
如果增加赋值语句,则会提示编译错误。
[code]void TestBoostScopedPtr() { boost::scoped_ptr<TestBody> smartPoint1(new TestBody(1)); if(smartPoint1.get()) { smartPoint1->PrintInfo(); smartPoint1->SetInfo("TestBoostScopedPtr"); smartPoint1->PrintInfo(); boost::scoped_ptr<TestBody> smartPoint2; smartPoint2 = smartPoint1; //编译错误 } }
查看源码实现,发现赋值语句声明为private
[code]template<class T> class scoped_ptr // noncopyable { private: T * px; scoped_ptr(scoped_ptr const &); scoped_ptr & operator=(scoped_ptr const &); typedef scoped_ptr<T> this_type; void operator==( scoped_ptr const& ) const; void operator!=( scoped_ptr const& ) const; public: }
boost::shared_ptr使用示例:
[code]void TestBoostSharedPtr() { boost::shared_ptr<TestBody> smartPoint1(new TestBody(1)); if(smartPoint1.get()) { smartPoint1->PrintInfo(); smartPoint1->SetInfo("TestBoostSharedPtr"); cout<<"use_count Point1:"<<smartPoint1.use_count()<<endl; boost::shared_ptr<TestBody> smartPoint2; smartPoint2 = smartPoint1; smartPoint2->PrintInfo(); smartPoint1->PrintInfo(); cout<<"use_count Point1:"<<smartPoint1.use_count()<<endl; cout<<"use_count Point2:"<<smartPoint2.use_count()<<endl; } cout<<"use_count Point1:"<<smartPoint1.use_count()<<endl; }
执行结果:
boost::scoped_array使用示例:
[code]void TestBoostScopedArray() { boost::scoped_array<TestBody> smartPoint(new TestBody[3]); if(smartPoint.get()) { smartPoint[0].PrintInfo(); smartPoint[1].PrintInfo(); smartPoint[2].PrintInfo(); smartPoint[0].SetInfo("TestBoostSharedPtr0"); smartPoint[1].SetInfo("TestBoostSharedPtr1"); smartPoint[0].PrintInfo(); smartPoint[1].PrintInfo(); } }
运行结果:
和scoped_ptr类似,赋值运算符被声明为私有。 ->改为用。标识。
相关文章推荐
- 深入理解c语言——‘\0’ ,‘0’, “0” ,0之间的区别
- c++11 std::bind使用
- c++选择文件夹对话框
- CHAP算法C++实现
- C /C++标准库 - <cstdio>(stdio.h)
- 如何学好C++语言
- “21天教你学会C++”
- 6个变态的C语言Hello World程序
- 如何学好C语言
- 算法练习 - 五笔编码
- c语言: Standard C 语言标准函数库
- C语言数学函数ceil(), floor(), round()
- 复制构造函数,赋值操作符,深浅复制,数组转换成vector数据
- C++Exception知识整理
- C++String知识整理
- SIP协议详解&eXosip源码库用法分析
- 个人学习c++的经验!
- C++ iterator知识整理
- C++11: unordered_map
- C/C++语言之由数字26引起的文件的数据保存与读取调试。