Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Exception while pushing back a sf::Text with sf::Font  (Read 3262 times)

0 Members and 1 Guest are viewing this topic.

4B

  • Newbie
  • *
  • Posts: 20
    • View Profile
Exception while pushing back a sf::Text with sf::Font
« 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.
« Last Edit: April 10, 2014, 08:19:25 pm by 4B »
If you're going to response to any of my comments, please avoid this smily: ";)"

I'd be grateful, thanks.

Jesper Juhl

  • Hero Member
  • *****
  • Posts: 1405
    • View Profile
    • Email
Re: Exception while pushing back a sf::Text with sf::Font
« Reply #1 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.
« Last Edit: April 10, 2014, 08:25:27 pm by Jesper Juhl »

4B

  • Newbie
  • *
  • Posts: 20
    • View Profile
Re: Exception while pushing back a sf::Text with sf::Font
« Reply #2 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
If you're going to response to any of my comments, please avoid this smily: ";)"

I'd be grateful, thanks.

 

anything