vendredi 26 mars 2021

C++ Override Destructor and ownership transfer of a member variable

I am not very proficient in C++. So I'll explain my problem as clearly as possible and when you are answering,please do some explanation.

So my problem involves 2 classes(A and B) with another class in a framework which I don't have access to. A has a pointer to B and B has a pointer to the A (raw pointers). The following show the interactions between the 2 classes.

class A {
  public:
    void method(){
      this->b_ = new B(this);
      SomeServiceClass::doSomething(std::unique_ptr<B>(this->b_));
    }

  private:
    B *b_;
}

class B {
  public:
    B(A *a){
      this->a_ = a;
    }
    someOtherMethod(){
    }

  private:
    A *a;
}

So what really happens is, A creates first, and inside a method() of A , I create B and pass the B as a unique_ptr to some other method implemented in another class of a framework(which I don't have access). So that way I transfer ownership of B to that other class. But during the lifetime of A, I want to access B's other methods. That is why I keep a raw pointer to B in the class A. (I could have used a shared_ptr instead but that SomeServiceClass::doSomething requires a unique_ptr). But my question is at the time A is destroyed. Should I override the destructor of A and assign this->b_ = null ? Or maybe delete ? Thanks in advance

Aucun commentaire:

Enregistrer un commentaire