shared_from_this called from constructor

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

    There is no need for shared_ptr in your code (as you show it and explain it). A shared_ptr is only appropriate for shared ownership.

    Your b_class doesn't own it's a_class, in fact is even outlived by it, so it should merely keep an observing pointer.

    If b_class is polymorphic and the manipulations of a_class involve altering its b_class pointer, you should use a unique_ptr:

    class a_class;
    class b_class
    {
      friend class a_class;
      a_class* mya;
      b_class(a_class*p)
      : mya(p) {}
    public:
      virtual~b_class() {}   // required for unique_ptr to work
      virtual void fiddle(); // do something to mya
    };
    
    class a_class
    {
      std::unique_ptr myb;
    public:
      a_class()
      : myb(new b_class(this)) {}
      template
      void change_myb()
      {
        myb.reset(new B(this));
      }
    };
    

提交回复
热议问题