zoukankan      html  css  js  c++  java
  • smart pointer shared_from_this的使用

    shared_ptr     enable_shared_from_this

    一种避免内存泄漏的方式是, always use a named smart pointer variable to hold the result of new

    shared_ptr<T>  p(new T);

    http://hi.baidu.com/jrckkyy/blog/item/ac3e5511fa4a59caa6ef3ff1.html    这篇文章讲了shared_from_this几个值得注意的地方, 看了几次,然后去翻阅了下源码,搞明白了

    boost文档中首先讲了enable_shared_from_this的作用 : The header <boost/enable_shared_from_this.hpp> defines the class template enable_shared_from_this. It is used as a base class that allows a shared_ptr to the current object to be obtained from within a member function.

    1. enable_shared_from_this<D> 作为D的基类, 这样D就继承了它的两个public函数,  shared_ptr<D> shared_from_this() ;  const shared_ptr<D>  shared_from_this  const ();

    2. D对象本身是不可以直接调用 shared_from_this()的, 在boost的代码设计中, D继承自 enable_shared_from_this<D> 的 private成员  weak_ptr<D> weak_this_  是从第三方函数调用D._internal_accept_owner(shared_ptr<D> const * Dptr,  D * pD)  来初始化, 而这个第三方函数是在 shared_ptr.hpp中实现的, 且由 shared_ptr<>的构造函数调用(很容易的把this传过去)

    以下代码例子

     1 #include <boost/shared_ptr.hpp>
    2 #include <boost/enable_shared_from_this.hpp>
    3 #include <iostream>
    4
    5 using namespace std;
    6 using namespace boost;
    7
    8 class WY : public enable_shared_from_this<WY>{
    9 public:
    10 WY (int i):i_(i) { cout << "WY's constructor" << endl; }
    11
    12 int i (){return i_;}
    13
    14 shared_ptr<WY> get_shared_ptr (){
    15 cout << "in get_shared_ptr ==> i = " << i_ << endl;
    16 return shared_from_this();
    17 }
    18 private :
    19 int i_;
    20 };
    21
    22 int main ()
    23 {
    24 WY wy(6); //这个wy对象实际上它的成员(继承自enable_shared_from_this<WY>) weak_ptr<WY>, 并有被初始化, 所以调用wy.shared_from_this()会抛错
    25 shared_ptr<WY> ptr(new WY(5)); //这个ptr所持有的WY, 其weak_ptr<WY>, 是初始化过的
    26 shared_ptr<WY> p = ptr->shared_from_this();
    27 ptr->get_shared_ptr();
    28 wy.get_shared_ptr();
    29 p = wy.shared_from_this();
    30 }

    24 行的 wy中的 weak_ptr没有被初始化, 25行ptr是初始化过的

    程序到28行的时候打印出   in get_shared_ptr  i = 6 之后异常退出, 即只要用 wy调用 shared_from_this 程序即异常退出

    关于上面第二点中的源代码剖析是针对 1-46-1来说的, 当我翻看以前版的源码时, 发现并不是这样实现的, 并没_internal_accept_owner 这个函数, 所以我们只需记住的时boost为外提供的使用方式, 那就是要  shared_ptr<D>  pD的持用的 D, 其中的weak_this_才是初始化过的, 才可调用其 shared_from_this, 以这样的方式   pD->shared_from_this()

  • 相关阅读:
    【转】字典转模型需要注意的问题,以及第三方框架来处理字典转模型
    【转】使用SOAP访问Web服务
    Foundation框架2
    Foundation框架1
    什么是Protocol
    什么是Block
    什么么是Category
    ARC
    autorelease简介
    循环retain
  • 原文地址:https://www.cnblogs.com/livingintruth/p/2367253.html
Copyright © 2011-2022 走看看