SFML community forums

Help => Graphics => Topic started by: 4B on April 10, 2014, 08:14:09 pm

Title: Exception while pushing back a sf::Text with sf::Font
Post by: 4B on April 10, 2014, 08:14:09 pm
Hello.

My current code to draw a button looks like this:

namespace foo
{
 std::vector<std::pair<sf::Text, sf::RectangleShape>> buttons;
 void newButton(...)
 {
  sf::Font bla;
  bla.loadFromFile("...");

  sf::text blub;
  blub.setFont(bla);

  buttons.push_back(std::make_pair(blub,  rectangle));
  //I think i can leave the rectangle-initialization out, because this works fine
 }
 void drawButtons(sf::RenderWindow &window)
 {
  for(std::pair<sf::Text, sf::RectangleShape> b : buttons)
  {
   window.draw(b.second);
   window.draw(b.first); //It fails here, because I set the Font
  }
 }
}
 

What I'm doing wrong? Obviously I'm not supposed to add the font before pushing it on a vector, but I need the font set[complet size of the sf::Text] for the rectangle-initialization.
Title: Re: Exception while pushing back a sf::Text with sf::Font
Post by: Jesper Juhl on April 10, 2014, 08:20:14 pm
Your font is allocated on the stack inside newButton(). As soon as you return from the function it is destroyed, leaving the copy of your text that you push into buttons to then refer to a deallocated object - it's downhill from there.

Edit: in the future, you'd do everyone a favour if you included the *exact* error messages/exception texts that you get with your posts. It would also be good if your code was an actually compilable minimal example that people could try out for themselves.
Title: Re: Exception while pushing back a sf::Text with sf::Font
Post by: 4B on April 10, 2014, 08:33:44 pm
Thanks. So I just had to define my sf::Font outside the function.  :-[

Well, sure I will post a "runable" code-snippet in the future, but since the error was already found I just wanted to know how to fix it.


-Thread can be closed