Tuesday, 10 September 2013

Templates and lazy initialization

Templates and lazy initialization

I have a UIManager that manages a series of classes that inherit from a
single UI class. Currently, it works something like this, where the
individual UIs are initialized lazily and are stored statically:
class UIManager
{
public:
UIManager(); // Constructor
virtual ~UIManager(); // Destructor
template <typename T>
T *getUI()
{
static T ui(); // Constructs T, stores result in ui when
// getUI<T>() is first called
return &ui;
}
}
Called with:
getUI<NameEntryUI>()->activate();
or
getUI<MenuUI>()->render();
I am considering a design change that would allow me to have more than one
player, hence more than one game window, hence more than one UIManager. I
want all my constructed ui objects to be cleaned up when the UIManager is
deleted (currently, because the ui objects are static, they stick around
until the program exits).
How can I rewrite the above to remove the ui objects when UIManager is
killed?

No comments:

Post a Comment