Boost logo

Boost :

From: JH (jupiter.hce_at_[hidden])
Date: 2019-08-02 03:30:52


Hi,

I have a derived base class:

class Base : boost::enable_shared_from_this<Base> {
public:
    Base();
    virtual ~Base();
    virtual boost::shared_ptr<Base> SharedFromThis(void) {return
shared_from_this();}
private:
}

class Derived : public Base {
public:
    Derived();
    ~Derived();

// boost::shared_ptr<Derived> SharedFromThis(void) {return
boost::static_pointer_cast<Derived>(shared_from_this());}
private:

};

Applications are sharing the derived class, it can either use
shared_ptr<Derived> or shared_ptr<Base> by calling the
SharedFromThis(), three options:

(1) Don't define derived class own SharedFromThis(), always call Base
SharedFromThis() to pass shared_ptr<Base> as Derived shared_ptr, the
reference count will be shared_ptr<Base>.

(2) Define derived class its own SharedFromThis() and pass
shared_ptr<Derived> to applications:

boost::shared_ptr<Derived> SharedFromThis(void) {return
boost::static_pointer_cast<Derived>(shared_from_this());}

That one cannot be virtual as conflicted to Base SharedFromThis(), the
reference count will always be boost::shared_ptr<Derived>

(3) Mixed both boost::shared_ptr<Derived> and boost::shared_ptr<Base>
in applications, that could be a bad option to cause segmentation as
one shared_ptr could be ended before another shared_ptr.

Which option will be safer?

Thank you.

Kind regards,

- jupiter


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk