#include <boost/shared_ptr.hpp>

 

共享指针

这个智能指针命名为boost::shared_ptr,定义在boost/shared_ptr.hpp里。智能指针boost::shared_ptr基本上类似于boost::scoped_ptr。关键不同之处在于boost::shared_ptr不一定要独占一个对象。它可以和其他boost::shared_ptr类型的智能指针共享所有权。在这种情况下,当引用对象的最后一个智能指针销毁后,对象才会被释放。

因为所有权可以在boost::shared_ptr之间共享,任何一个共享指针都可以被复制,这跟boost::scoped_ptr是不同的。这样就可以在标准容器里存储智能指针了--你不能在标准容器中存储std::auto_ptr,因为它们在拷贝的时候传递了所有权。

 

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <vector>
 4 #include <boost/shared_ptr.hpp>
 5 
 6 void show(boost::shared_ptr<int>p)
 7 {
 8     std::cout << *p << std::endl;
 9 }
10 
11 void main()
12 {
13     std::vector<boost::shared_ptr<int>>v;
14 
15     boost::shared_ptr<int>p1(new int(11));
16     boost::shared_ptr<int>p2(new int(12));
17     boost::shared_ptr<int>p3(new int(13));
18 
19     v.push_back(p1);
20     v.push_back(p2);
21     v.push_back(p3);
22     
23     for_each(v.begin(), v.end(), show);
24 }

 

使用boost::shared_ptr的类型初始化新对象,是浅拷贝

 

 1 #include <iostream>
 2 #include <boost/shared_ptr.hpp>
 3 
 4 class runclass
 5 {
 6 public:
 7     int i = 0;
 8 public:
 9     runclass(int num) :i(num)
10     {
11         std::cout << "i creator " << i << std::endl;
12     }
13     ~runclass()
14     {
15         std::cout << "i delete " << i << std::endl;
16     }
17     void print()
18     {
19         std::cout << "i=" << i << std::endl;
20     }
21 };
22 
23 void show(boost::shared_ptr<int>p)
24 {
25     std::cout << *p << std::endl;
26 }
27 
28 void main()
29 {
30     boost::shared_ptr<runclass>p1(new runclass(10));//有调用构造函数
31 
32     boost::shared_ptr<runclass>p2(p1);//浅拷贝,没有调用构造函数
33     boost::shared_ptr<runclass>p3(p1);//浅拷贝,没有调用构造函数
34 
35     p1.reset(new runclass(12));//有调用构造函数
36 
37     p1->print();
38     p2->print();
39     p3->print();
40 }

 

转载于:https://www.cnblogs.com/denggelin/p/5768682.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值