Static method of creating an object instead of a constructor

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: // ... Button(); public: // ... static std::shared_ptr<Button> create(); } std::shared_ptr<Button> Button::create() { std::shared_ptr<Button> bt = std::shared_ptr<Button>(new Button()); GUIObjectsStorage::Instance().addObject(bt); return bt; } 

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?

+7
source share
2 answers

This is the classic use of Factory to create objects.

However, you may not need this. Do you know when widgets are no longer needed? Such GUI managers often do. If so, the commentator is right: designate the owner of the object, let it delete it, and you are set up.

+2
source

You can inherit from enable_shared_from_this .

Then, after you have shared_ptr for the object, you can use shared_from_this () to get the shared_ptr that the object contains.

0
source

All Articles