Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which shared pointer should be weak pointer in a ring or a cycle

If we have a Parent class that has a reference to a Child Class (shared pointer) and the Child Class also has a reference to the Parent Class (again with a shared pointer) we have to make one of these two smart pointers a weak pointer.

But how we decide which of these two pointers should be a weak pointer?

Also when a weak pointer points to 0 (when the shared count is 0), is not a situation where an object deleted when we may still need access to it? ok, i get that at least we know that the object is not there and that we should not try to access it, but is this enough?

like image 930
siwmas Avatar asked Jun 03 '26 07:06

siwmas


1 Answers

Think about the liftime of the objects.

If the Child can't out-live the Parent, then the Parent hold a shared pointer to the Child.

Shared pointers define the life-time hierarchy.

like image 190
Yochai Timmer Avatar answered Jun 05 '26 01:06

Yochai Timmer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!