shared_from_this called from constructor

前端 未结 7 1971
一生所求
一生所求 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:28

    a_class is responsible for creating and destroying b_class instances

    ...

    a_class instance "survives" b_class instances.

    Given these two facts, there should be no danger that a b_class instance can attempt to access an a_class instance after the a_class instance has been destroyed as the a_class instance is responsible for destroying the b_class instances.

    b_class can just hold a pointer to it's associated a_class instance. A raw pointer doesn't express any ownership which is appropriate for this case.

    In this example it doesn't matter how the a_class is created, dynamically, part of a aggregated object, etc. Whatever creates a_class manages its lifetime just as a_class manages the lifetime of the b_class which it instantiates.

    E.g.

    class a_class;
    
    class b_class
    {
    public:
        b_class( a_class* a_ ) : a( a_ ) {}
    private:
        a_class* a;
    };
    
    class a_class
    {
    public:
        a_class() : b( new b_class(this) ) {}
    private:
        boost::shared_ptr b;
    };
    

    Note, in this toy example there is no need for a shared_ptr, an object member would work just as well (assuming that you don't copy your entity class).

    class a_class
    {
    public:
        a_class() : b( this ) {}
    private:
        b_class b;
    };
    

提交回复
热议问题