Search code examples
c++sdl-2sdl-ttf

"Undefined size" error when defining a vector containing TTF_Font variables in C++


I have tried defining a vector within a class containing a number of TTF_Font variables like so: std::vector<TTF_Font> *fonts = &std::vector<TTF_Font>(); This gives me an error that states, "'_TTF_Font *const ': unknown size." I have also tried adding an integer inside of the parenthesis to define a size, but this doesn't help. Additionally, I have defined multiple other variables in the same fashion (e.g. std::vector<int> *xposes = &std::vector<int>();) and they work perfectly fine. Any idea as to what I could do to get the vector containing fonts to work (preferably without having to define a size)?


Solution

  • Creating a vector object using std::vector<int> *xposes = &std::vector<int>(); will not work correctly, because xposes is set point to a temporary object, that gets destroyed right afterwards. In some simple cases the program might still run correctly depending on the compiler, but it is undefined behavior because the vector object's destructor was called, and xposes is a dangling pointer pointing to an object that no longer exists.

    Instead std::vector<int> xposes; should be used.

    TTF_Font is an opaque type, meaning it is a struct whose definition is not available. So only pointers TTF_Font* can be used by a program using SDL_ttf. The error message means that sizeof(TTF_Font) does not work, and because of this it is not possible to create an std::vector<TTF_Font>. Instead a vector of pointers std::vector<TTF_Font*> would work.