mardi 5 décembre 2017

C++ shared ptr release on multiple references

I have an hierarchy where A is an abstract class and B, C, and D are descendants of A. I have a class Controller (MVC pattern) with a pointer to A. Look:

class Controller {

private: 
 int it;
 std::shared_ptr<A> theBase;

public:
 void doCall();
//more code

}

Then inside the doCall I do this:

void doCall() {

  switch (it) {
    case 4:
      theBase = std::make_shared<B>( B(8) );
      break;
    case 3:
      theBase = std::make_shared<C>( C(6) );
      break;
    default:
      theBase = std::make_shared<D>( D(0) );
      break;
    }

  theBase->method();

}

In this way I can properly use smart pointers and I can use inheritance to get the class that I need according to the value of it. Suppose that I call this code:

Controller x;
x.doCall();
x.doCall();

I am calling the doCall() twice so I am going in the switch case twice. This means that std::make_shared is called twice and assigned to theBase. Is this safe?

When I call doCall for the first time, I have a shared pointer. The second time I am assigning to theBase another std::make_shared and I wonder: is the old pointer (the one of the first call) destroyed and a new one is created? Or I have to do something like

if (*theBase != nulptr) {
  theBase.reset(); //delete the old one;
}

switch (it) { /* ... */}

Each time that doCall is called I have to create a new object that is a subclass of theBase. Am I doing it correctly?

Aucun commentaire:

Enregistrer un commentaire