Hi, I have seen several responses to this question before, ranging from "Never! Smart pointers are evil!" to "Only when you have resources that the main framework does not directly track." to "Always, unless there is need for extreme performance, or using them is a practical impossibility."
I have two types of object, say Root and Entity. Root creates and "owns" Entities, i.e. Entity will not operate if the Root object has been destroyed. References to both types of object can be passed to the user. If I use smart pointers, the user controls the lifetime of the Entities, but once Root has been destroyed, none of the Entities will function any more. The way I see to handle this is to store a weak_ptr to Root in each Entity. Every time an Entity needs Root to exists to function properly, it can check the existence of Root through its weak_ptr. The problem with this, is if there is another class SubEntity which is owned in a similar way by Entity. Thus, if Root is destroyed, the Entities will still exist, and SubEntity will have to check its validity by somehow checking the entire chain all the way down to Root (this could be done in various ways). This seems very long winded, but it does mean that the framework can deal easily with invalid function calls by the user.
The problem I have is that in my framework, nearly all the classes exist in hierarchical patterns such as the above. If fact, I can imagine that many frameworks operate like this, and this is why I am unsure about the use of shared_ptrs in general. Is this a situation where it would be best not to use smart pointers, and have the risk of the user dereferencing an invalid pointer? Or is using smart pointer here worth the effort? Or maybe I am missing something completely.
Thanks for your time, I greatly appreciate it.