I am creating a GUI in my C ++ application, and I have a class called GUIObject , which is the base class for all other components like Button , CheckBox , Window , etc.
I also have a GUIObjectsStorage class, which consists of all GUIObject that are created. So far I have worked with raw pointers, so I only had this constructor for the GUIObject class:
GUIObject::GUIObject() : { GUIObjectsStorage::Instance().addObject(this); }
And that was good for my needs, because whenever I wanted to access a specific object, I just took it from GUIObjectsStorage . But now I'm trying to use smart pointers, so GUIObjectsStorage now stores the std::shared_ptr<GUIObject> instead of raw pointers, and I cannot use my constructor as I used to do it:
GUIObject::GUIObject() : { GUIObjectsStorage::Instance().addObject(std::shared_ptr<GUIObject>(this)); }
because for example:
// Somewhere in code std::shared_ptr<Button> bt = std::shared_ptr<Button>(new Button());
Basically, I now have two shared_ptr (one here, the second in GUIObjectsStorage , because it was added to the Button constructor), which both have a reference count = 1, but both point to the same object in memory, then if one of them dies, the object itself is also destroyed.
So, I came up with the idea of ββmaking a private constructor for all classes inheriting from GUIObject , and creating a static method that would create and return std::shared_ptr , and copy it to GUIObjectsStorage . That way I could have shared_ptr with reference count = 2, which is true:
class Button : public GUIObject { private:
By hiding the constructor, I could be sure that no one would create an object in any other way than using the create() method.
But is this a good way to develop it? If not, what could be the best solution for this problem?