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 }
  • 相关阅读:
    lua判断字符串包含另一个字符串
    expect使用技巧
    Linux expect
    expect正则捕获返回结果
    修改alpine Linux的Docker容器的时区
    Dockerfile镜像优化,减小镜像
    Sed在匹配行前后加入一行
    scp的使用以及cp的对比
    rsync 的用法
    傅里叶系列(一)傅里叶级数的推导 (转)
  • 原文地址:https://www.cnblogs.com/denggelin/p/5768682.html
Copyright © 2011-2022 走看看