Move to more memory safe implementation of widget holding

This commit is contained in:
2025-12-12 15:35:32 +02:00
parent ddc7898a78
commit 8e276ab2ab
6 changed files with 16 additions and 17 deletions

View File

@@ -4,6 +4,7 @@
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
@@ -17,14 +18,16 @@
using std::cout;
using std::endl;
using std::map;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
using nlohmann::json;
void init_builders(map<string, Widget*(*)(const json&)>& widget_builders)
void init_builders(map<string, unique_ptr<Widget>(*)(const json&)>& widget_builders)
{
widget_builders["text"] = &WidgetText::builder;
widget_builders["rect"] = &WidgetRect::builder;
widget_builders["text"] = &WidgetText::builder;
}
int main(int argc, char **argv)
@@ -41,8 +44,8 @@ int main(int argc, char **argv)
SDL_Surface* main_surface = nullptr;
vector<json> widgets_cfg;
vector<Widget*> widgets;
map<string, Widget*(*)(const json&)> widget_builders;
vector<shared_ptr<Widget>> widgets;
map<string, unique_ptr<Widget>(*)(const json&)> widget_builders;
ok = init_sdl();
if (!ok)
@@ -102,7 +105,7 @@ int main(int argc, char **argv)
}
// Construct and add widget to vector
Widget* widget = widget_builders[widget_name](j);
shared_ptr<Widget> widget = widget_builders[widget_name](j);
if (nullptr != widget)
{
widgets.push_back(widget);
@@ -113,7 +116,7 @@ int main(int argc, char **argv)
SDL_FillRect(main_surface, nullptr, SDL_MapRGBA(main_surface->format, 255, 255, 255, SDL_ALPHA_OPAQUE));
// Draw and apply all widgets
for (Widget* widget : widgets)
for (shared_ptr<Widget>& widget : widgets)
{
widget->draw();
SDL_Rect rect = widget->get_rect();
@@ -125,11 +128,6 @@ int main(int argc, char **argv)
IMG_SavePNG(main_surface, output_filename.c_str());
cleanup:
// Destroy All Widgets
for (Widget* widget : widgets)
{
delete widget;
}
widgets.clear();
clean_sdl();