I have a vector array of a class that's giving me some crap. I would beat it up, but that might result in some innocent circuits getting damaged.
Class:
class Font {
public:
Font();
~Font();
int style;
int ptSize;
std::string name;
TTF_Font *font;
};
Font::Font()
{
style = TTF_STYLE_NORMAL;
ptSize = 0;
name = "";
font = NULL;
}
Font::~Font()
{
// Access violation
TTF_CloseFont( font );
}
Code:
std::vector<Font> fonts;
SDL_Surface *renderText( std::string fontName, int ptSize, std::string text, const SDL_Color *textColor, const SDL_Color *backroundColor, int flags )
{
// cut
if( fontElement == -1 ) {
std::string fileName = "c:\\windows\\fonts\\" + fontName;
// class constructor called here
fonts.resize( fonts.size() + 1 );
fontElement = fonts.size() - 1;
fonts[ fontElement ].ptSize = ptSize;
fonts[ fontElement ].name = fontName;
fonts[ fontElement ].font = TTF_OpenFont( fileName.c_str(), ptSize );
if( fonts[ fontElement ].font == NULL ) {
return NULL;
}
if( fontStyle != TTF_STYLE_NORMAL ) {
fonts[ fontElement ].style = fontStyle;
TTF_SetFontStyle( fonts[ fontElement ].font, fontStyle );
}
// class destructor called here
}
// cut
// no error here
if( flags & FH_BLENDED ) {
return TTF_RenderText_Blended( fonts[ fontElement ].font, text.c_str(), fgColor );
}
else if( flags & FH_SHADED ) {
return TTF_RenderText_Shaded( fonts[ fontElement ].font, text.c_str(), fgColor, bgColor );
}
else if( flags & FH_SOLID ) {
return TTF_RenderText_Solid( fonts[ fontElement ].font, text.c_str(), fgColor );
}
return NULL;
}
The problem is that right after the if statement the class destructor is called. Oddly enough, when I use fonts[].font later, I don't get an error; I only get the access error after the program attempts to terminate, because it calls the destructor again. It goes something like this:
constructor
loads font
destructor
renders text - renders with a closed font??
back to main
display text - displays fine
destructor - error happens here
I can post the rest of the source code, if necessary. What stupid thing am I missing?