boost enable shared from this


Code Example

#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

using namespace std;
using namespace boost;

/*
enable_shared_from_this has become part of C++ 11 standard.

https://blog.csdn.net/csfreebird/article/details/8282518
https://stackoverflow.com/questions/712279/what-is-the-usefulness-of-enable-shared-from-this
*/

class Y : public boost::enable_shared_from_this<Y>
{
public:

    Y()
    {
        cout << "Y::Y()" << endl;
    }

    ~Y() 
    {
        cout << "Y::~Y()" << endl;
    }

    boost::shared_ptr<Y> f()
    {
        return shared_from_this();
    }

    boost::shared_ptr<Y> f_dangerous()
    {// lead to multiple release on same resouce
        return boost::shared_ptr<Y>(this);  // don't do this!
    }
};

void test_safe()
{
    boost::shared_ptr<Y> p(new Y);
    boost::shared_ptr<Y> q = p->f();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership

    /*
    Y::Y()
    Y::~Y()
    */
}

void test_dangerous()
{
    boost::shared_ptr<Y> p(new Y);
    boost::shared_ptr<Y> q = p->f_dangerous();
    assert(p == q);
    assert(!(p < q || q < p)); // p and q must share ownership

    /*
    Y::Y()
    Y::~Y()
    Y::~Y()
    */
}

int main()
{
    //test_safe();
    test_dangerous();
    return 0;
}

Reference

History

  • 20180523: created.

Author: kezunlin
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint polocy. If reproduced, please indicate source kezunlin !
评论
  TOC