智能指针:scoped_ptr and shared_ptr

 1 // boost_ptr.cpp : 定义控制台应用程序的入口点。
 2 //智能指针--scoped_ptr,shared_ptr
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include <string>
 7 #include <boost/scoped_ptr.hpp>
 8 #include <boost/shared_ptr.hpp>
 9 class ptr_test
10 {
11 public:
12     ptr_test()
13     {
14         std::cout <<"construct"<< std::endl;      
15     }
16     ~ptr_test()
17     {
18         std::cout << "destruct" << std::endl;
19     }
20     void process()
21     {
22         std::cout << "process...." << std::endl;
23     }
24 };
25 void boost_ptr()
26 {
27 /*    boost::scoped_ptr<ptr_test>  impl(new ptr_test());
28     impl->process();*/
29     /*scoped_ptr不能共享所有权,不能这样操作,编译出问题*/
30 /*    boost::scoped_ptr<ptr_test>  impl_new=impl;
31     std::cout << impl_new.get() << std::endl;*/
32     boost::shared_ptr<ptr_test>  sp(new ptr_test());
33     std::cout <<"sample now has "<< sp.use_count()<< " references"<<std::endl;
34     /*复制对象*/
35     boost::shared_ptr<ptr_test>  sp1=sp;
36     std::cout <<"sample now has "<< sp1.use_count()<< " references"<<std::endl;
37     sp.reset();
38     std::cout <<"reset sp , sample now has "<< sp1.use_count()<< " references"<<std::endl;
39     sp1.reset();
40     std::cout <<"reset sp1 "<<std::endl;
41 }
42 int _tmain(int argc, _TCHAR* argv[])
43 {
44     boost_ptr();
45     return 0;
46 }

运行结果:

construct
sample now has 1 references
sample now has 2 references
reset sp , sample now has 1 references
destruct
reset sp1
请按任意键继续. . .

从上面可以看出,scoped_ptr不能共享所有权,而shared_ptr可以共享所有权;当sp和sp1都释放对该对象所有权时,所管理的对象内存才释放。

你可能感兴趣的:(智能指针:scoped_ptr and shared_ptr)