Let's say I have an object Foo
that uses another object Bar
.
Many different Foo
could use the same Bar
.
When no Foo
references a Bar
, this Bar
is useless and should be destroyed.
Clearly, that's a perfect use case for a shared pointer :
class Foo
{
Foo() { m_bar = std::make_shared<Bar>(); };
Foo(const Foo& other) { m_bar = other.m_bar};
std::shared_ptr<Bar> m_bar;
}
class Bar
{
Bar(){};
}
Foo myfunc()
{
Foo foo1; //bar created
Foo foo2(foo1);
//do thing with foo1 or foo2
return foo2;
}
void main()
{
Foo foo = myfunc();
} //bar destroyed
As expected, the only Bar
object that has been created will be destroyed when the last Foo
object is destroyed, meaning at the end of my main in my example.
But now, I would like to keep track of all my Bar
s and have an access to them : I want a BarList
, vector of existing Bar
.
I may create the vector (like with a foo factory that also fills the vector), but I have problem with maintaining this list and especially removing from it the Bar
that have been destroyed.
Obviously I can't have a vector of shared pointer, because then use count never drops to 0.
I could store a weak pointer (or a raw?) but then I have another problem: after some times, my vector will be full of destroyed object.
Given that my Bar
are not aware of the BarList
, how could I be sure that when a Foo
is destroyed, if this triggers an Bar
destruction, then this bar will be removed from the BarList
?
Note that my Foo
s are aware of the BarList
(they have a link to it). But the only solution I have for now is a ugly use_count
hack : on foo destructor, if bar use_count is 1 (i.e. hold only by this current Foo
), then remove it from the list.
What would be the good design for that?