zoukankan      html  css  js  c++  java
  • #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 }
  • 相关阅读:
    django模型的crud操作
    django模型中的关系对应
    django中模型详解-字段类型与约束条件
    django中的模型详解-1
    运维自动化轻量级工具pssh
    zabbix告警使用sendEmail
    nginx正向代理,反向代理,透明代理(总结)
    nginx.conf的events,http段一般固定配置
    nginx实战2---浏览器设置缓存
    nginx之location
  • 原文地址:https://www.cnblogs.com/denggelin/p/5768682.html
Copyright © 2011-2022 走看看