lundi 28 octobre 2019

How to pass a pointer from unique_ptr to another object and manage the lifespan?

I'm sure there's a standard way to solve this problem, but I can't find it.

I have a Processor class which manages the lifespans of all objects. A Foo may be assigned to a Bar occasionally. But Bar needs to know when Foo is no longer available (has been removed by the Processor). What is the right way to achieve this?

class Processor {
  private:
    vector<unique_ptr<Foo>> foos;
    vector<unique_ptr<Bar>> bars;
};

class Bar {
  public:
    void AssignFoo(Foo* foo){ cur_foo = foo; }
  private:
    Foo* cur_foo = nullptr;
};

One option I can think of is to have a map in Processor which keeps track of the assignments, and have a function RemoveFoo in Bar but I'm wondering if there's any other way.

Aucun commentaire:

Enregistrer un commentaire