lundi 20 septembre 2021

Shared Ptr going out of scope

This is how the high level structure of my code looks like:

Class Animal {
  template<typename AnimalType>
  static shared_ptr<AnimalType> Create(AnimalType *ptr);
  std::weak_ptr<Animal> weak_ptr_;
};
template<typename AnimalType>
shared_ptr<AnimalType> Animal::Create(AnimalType *const ptr) {
  const shared_ptr<AnimalType> op(ptr);
  op->weak_ptr_ = std::weak_ptr<Animal>(std::static_pointer_cast<Animal>(op));
  return op;
}

Class Rabbit : Class Animal {

  static shared_ptr<Rabbit> Create() {
    return Animal::Create(new Rabbit());
  }
  void Run() {
    // Does a async call and mentions to call RunDone() upon completion.
  }
  void RunDone() {
    // Does something
  }
};

Another Class Task has access to both Animal and Rabbit classes:

Task() {  --> constructor
  animal_ = nullptr;  --> animal_ is a public data member of 
                          Task class
}
StartTask() {
  animal_ = Rabbit::Create();
  animal_->Run();
}

When Run is called, it does a async call with RunDone() as the callback. But the problem here is that the object is going out of scope after Run() is called and hence RunDone() is not getting called upon the async function completion. Why is this object going out of scope even if I am storing the shared pointer of Rabbit class in a global variable of the Task class? And also please let me know how I can prevent it from going out of scope. Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire