Search code examples
c++boostboost-asioshared-ptrweak-ptr

sub classing from enable_shared_from_this


I've a generic_connection

class generic_connection: public boost::enable_shared_from_this<generic_connection>

Now I want to subclass it and create

class agent_connection: public generic_connection

does agent_connection need to derive from boost::enable_shared_from_this<agent_connection> again ?


Solution

  • You dont need to derieve again. But, this has some problems, for example you cannot do call like this

    shared_from_this()->agent_connection__method()
    

    or this

    boost::bind(&agent_connection::method, shared_from_this())
    

    To solve this, you should do templated inheritance:

    template <typename T>
    class generic_connection : 
            public boost::enable_shared_from_this<T> {
    };
    
    class agent_connection : public generic_connection< agent_connection > {
    };
    

    This makes agent_connection more complicated, but you wont need to cast shared_ptr any time you use it.