Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

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.

like image 215
Plasty Grove Avatar asked Oct 28 '19 10:10

Plasty Grove


1 Answers

One way to do it is using std::shared_ptr and std::weak_ptr:

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

class Bar {
public:
    void AssignFoo(const std::weak_ptr<Foo>& foo){ cur_foo = foo; }
private:
    bool FooIsValid() const {
        return !cur_foo.expired();
    }  

    std::weak_ptr<Foo> cur_foo;
};

EDIT: tried earlier to use unique_ptr and raw pointers but it turn out wrong from the beginning so I removed it.

like image 161
bartop Avatar answered Oct 05 '22 19:10

bartop