I have a font class that will load glyphs from a .ttf to openGL textures using sdl. The class consists of individual textures for each glyph and will obviously render them in succession to create displayed text. I figure it's costly to keep loading the .ttf to an sdl surface and then, in turn, using the surface pixel data to generate an openGL texture. So, I have for my program, a KText
class that has a member: static std::vector<Font*> OpenedFonts;
When a new item that has inherited KText attempts to open a font, I scan the vector for the opened glyphs and then just return a pointer to the opened glyphs and just use the already made textures for all instances of that text (size/name/color).
The code is
bool KText::LoadFont() {
_Font = CheckOpenedFonts(); //_Font is KFont* pointer
if(_Font == NULL) {
_Font = new KFont;
_Font->LoadFont();
}
if(_Font == NULL) return false;
return true;
}
Clearly, not every time will I open a new font, so in my destructor I wouldn't want to simply use delete _Font
. For namely these two reasons: there is another KText object pointer to that same set of glyphs and it would be good to keep them in memory until the program terminates in case another object is created and attempts to use that font.
Is there a way to wait until all the instances of KFont
have left scope?
Thank you!
The solution was:
class KText {
private:
static int TextCnt;
public:
KText();
~KText();
};
//Implementation
static int KText::TextCnt = 0;
KText::KText() {
TextCnt++;
}
KText::~KText() {
TextCnt--;
if(TextCnt < 1) {
OpenedFonts* t = FntPnter; //FntPnter is a head pointer to the linked list of fonts
while(t != NULL ) {
FntPnter = t->Next;
delete t;
t = FntPnter;
}
}
}