I want to create two objects A
and B
, such that A.b()
returns a reference to B
if it is still alive, otherwise, null, and vice versa for B.a()
. Has this problem been solved in a standard or widely-used utility library somewhere before?
I've run into two separate instances of this problem recently. I'm particularly interested in solutions in C++ but it might be useful to see how Rust or other non garbage-collected languages approach this.
I think this be done using reference-counting (store A
and B
using std::shared_ptr
and keep std::weak_ptr
references), and I can also think of an approach that avoids that (manage the lifetimes of A
and B
using whatever method you prefer, and store both plain references as well as booleans indicating liveness; update the boolean inside B
when A
is deleted and vice versa; in multi-threaded context, add a lock). But my workplace discourages use of std::shared_ptr
, and the latter solution seems a little complex to me. I'm wonderingi f there's something simpler.