简体   繁体   中英

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?

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.

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.

No, you don't have to , you can if you think it will suits your design.

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

The object that can live and do his job without needing the other should store the 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?

If both object need each other to be alive when they are alive themselves, then keep a shared pointer in each of them. When these objects are done doing their job you just have to reset one shared pointer (usually the one contained in the most top level class) and it will create a cleaning cycle where all your instances are correctly destroyed if they are not used elsewhere.

PS: A design I find very helpful for this situations is to add start / stop member functions especially if you are using enable_shared_from_this which can't be called within the constructor, you can get more details on this design from boost asio's author .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM