shared_from_this called from constructor

前端 未结 7 1969
一生所求
一生所求 2021-02-03 21:31

I have to register an object in a container upon its creation. Without smart pointers I\'d use something like this:

a_class::a_class()
{
    register_somewhere(t         


        
7条回答
  •  北恋
    北恋 (楼主)
    2021-02-03 22:20

    Why don't you use http://www.boost.org/doc/libs/1_43_0/libs/smart_ptr/enable_shared_from_this.html

    struct a_class : enable_shared_from_this {
        a_class() {
            shared_ptr ptr(this);
            register_somewhere(ptr);
        }
    };
    

    Update: here is a complete working example:

    #include 
    #include 
    
    struct a_class;
    boost::shared_ptr pa;
    
    void register_somewhere(boost::shared_ptr p)
    {
        pa = p;
    };
    
    struct a_class : boost::enable_shared_from_this {
    private:
        a_class() {
            printf("%s\n", __PRETTY_FUNCTION__);
            boost::shared_ptr ptr(this);
            register_somewhere(ptr);
        }
    
    public:
        ~a_class() {
            printf("%s\n", __PRETTY_FUNCTION__);
        }
    
        static boost::shared_ptr create()
        {
            return (new a_class)->shared_from_this();
        }
    };
    
    int main()
    {
        boost::shared_ptr p(a_class::create());
    }
    

    Note the factory function a_class::create(). Its job is to make sure that only one reference counter gets created. Because

    boost::shared_ptr p(new a_class);
    

    Results in creation of two reference counters and double deletion of the object.

提交回复
热议问题