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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With