How to impl boost::enable_shared_from_this?

Help
2008-03-05
2013-04-08
  • Hi,I am study the Loki::SmartPtr,

    I think the boost::enable_shared_from_this is very good implement,
    we can get the smart pointer form a originality pointer of a class,
    then we can use this function from the class's member function.
    like this:

    #include <boost/smart_ptr.hpp>
    #include <boost/enable_shared_from_this.hpp>

    class CObj : public boost::enable_shared_from_this<CObj>
    {
    public:
        CObj()
        {
            printf("CObj");
        }
        ~CObj()
        {
            printf("CObj");
        }

        void Action();
        void Action2();
    };

    void Func(boost::shared_ptr<CObj> ptr)
    {
        ptr->Action2();
    }

    void CObj::Action()
    {
    ////////////////////////////

        boost::shared_ptr<CObj> ptr = shared_from_this();
        Func(ptr);

    ////////////////////////////
    }
    void CObj::Action2()
    {
        printf("Action2");
    }

    int main()
    {
        boost::shared_ptr<CObj> ptr(new CObj);
        ptr->Action();
    }

    thanks!