Note that there are some explanatory texts on larger screens.

plurals
  1. POfreeing memory when all instances of a class are destroyed
    primarykey
    data
    text
    <p>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 <code>KText</code> class that has a member: <code>static std::vector&lt;Font*&gt; OpenedFonts;</code> </p> <p>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). </p> <p>The code is</p> <pre><code>bool KText::LoadFont() { _Font = CheckOpenedFonts(); //_Font is KFont* pointer if(_Font == NULL) { _Font = new KFont; _Font-&gt;LoadFont(); } if(_Font == NULL) return false; return true; } </code></pre> <p>Clearly, not every time will I open a new font, so in my destructor I wouldn't want to simply use <code>delete _Font</code>. 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.</p> <p>Is there a way to wait until all the instances of <code>KFont</code> have left scope?</p> <p>Thank you!</p> <p>The solution was:</p> <pre><code>class KText { private: static int TextCnt; public: KText(); ~KText(); }; //Implementation static int KText::TextCnt = 0; KText::KText() { TextCnt++; } KText::~KText() { TextCnt--; if(TextCnt &lt; 1) { OpenedFonts* t = FntPnter; //FntPnter is a head pointer to the linked list of fonts while(t != NULL ) { FntPnter = t-&gt;Next; delete t; t = FntPnter; } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload