I have a class which inherits from enable_shared_from_this. It has shared_ptr
s to child objects and there's one "root" object, so the whole hierarchy is managed by shared_ptr. This way an object can have multiple parents and be destructed safely.
I started writing a constructor, and then I realized the user should be managing the objects using std::shared_ptr
like I do internally, and like I saw in some existing libraries, for example gtkmm. So I can do what I see others do: hide the constructor, and write a static member function create() which returns a shared_ptr
to the new object. Clearly create() is very useful, because without it I need to call std::make_shared()
or, later, std::shared_from_this()
.
But should I hide the constructor, and why? I can guess some good reasons, for example it enforces the user use the shared_ptr, otherwise the object gets deleted, so it's a guarantee the user doesn't use an "orphan" object which isn't managed by shared_ptr. And it ensures the user doesn't forget to manually create a shared_ptr, because forgetting means the object is deleted, even if it was copied (deep copy, not a copy of a pointer), and then the user notices that very quickly.
Another interesting option is to NOT have the create() static method, and instead have an add_child() method to be the only way to create a new object. This guarantees it's linked to the hierarchy. The problem: flexibility. If someone wants to use an object separately, it's impossible, unless you derive the class.
What would you do/should I do? hide/not hide the ctor? add_child()
? create()
?