Reputation: 412
I am trying to make a GUI library. And I wish the following statement valid. Plus the user does not responsible for releasing memory.
// Create a GUI context
xGUI::xGUI gui(800, 600);
// gui.objects is a std::map<std::string, IWidget *>
gui.objects["btn"] = new xGUI::Button("Close", 50, 50);
gui.objects["btn2"] = gui.objects["btn"]->clone();
// Block end gui will free all the objects.
As you can see, clone is ugly but needed.(Is there any solution?) However this clone will use new to allocate memory in the library. then be free by dtor of xGUI which I wrote in header file. new in the library and delete in the main program... Will it be a problem??
Upvotes: 0
Views: 69
Reputation: 2555
Don't use pointers, but wrappers that behave similar to reference counting smart pointers and expose the required interface:
// Create a GUI context
xGUI::xGUI gui(800, 600);
// gui.objects is a std::map<std::string, IWidget *>
gui.objects["btn"] = xGUI::Button("Close", 50, 50);
gui.objects["btn2"] = gui.objects["btn"].clone();
Look ma, no pointers, no memory leaks.
Have a look at this json library, with polymorphic behavior, but without the need for the user to cope with dynamic memory allocation: https://github.com/TorstenRobitzki/Sioux/blob/master/source/json/json.h
Upvotes: 0
Reputation: 133609
Instead that using an std::map<std::string, IWidget*>
think about using a std::map<std::string, std::unique_ptr<IWidget>>
.
An std::unique_ptr<T>
is a special wrapper around an object that will automatically manage the destruction of the object when the unique_ptr
itself is destroyed. This makes managing memory on object which have a single owner (like it seems in your case) quite trivial.
Upvotes: 3