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

Author Topic: sf::Text::Font pointers reset to NULL  (Read 1819 times)

0 Members and 1 Guest are viewing this topic.

AlexBratosin

  • Newbie
  • *
  • Posts: 2
    • View Profile
sf::Text::Font pointers reset to NULL
« on: August 21, 2017, 11:59:11 pm »
Hey people!

I'm trying to understand why I keep getting an access violation while drawing a sf::Text.
I've managed to replicate my current scenario in the code below.
Basically, in that for loop, the pointers of the font present in a.text (m_library...) are set correctly but after the first iteration if I go ahead and check objects[0].text, those pointers are reset to NULL.
Could you please explain to me this behavior?

Thanks a lot!

Note: please ignore the ugliness of this code as it's only meant for demonstration purposes :)

class myClass
{
public:
        sf::Text text;
        sf::Font font;
};

void main()
{
        std::vector<myClass> objects;
        sf::Font f;
        f.loadFromFile("arial.ttf");
        for (int i = 0; i < 10; i++)
        {
                myClass a;
                a.font = f;
                a.text.setFont(a.font);
                objects.push_back(a);
        }
        sf::RenderWindow window(VideoMode(100, 100), "window");
        while (window.isOpen())
        {
                window.clear();
                for (myClass a : objects)
                {
                        window.draw(a.text);
                }
                window.display();
        }
}
 
« Last Edit: August 22, 2017, 12:00:53 am by AlexBratosin »

Laurent

  • Administrator
  • Hero Member
  • *****
  • Posts: 32504
    • View Profile
    • SFML's website
    • Email
Re: sf::Text::Font pointers reset to NULL
« Reply #1 on: August 22, 2017, 01:28:06 pm »
As you add more and more elements to your std::vector, it will sometimes move them elsewhere in memory (to find more space). So the myClass instances that end up in your vector are not those that you pushed back in the for loop, they are copies of them. Therefore, your sf::Text instances end up pointing to sf::Font instances that no longer exist -- only copies of them exist, elsewhere in memory.

Two strategies exist to avoid this problem:

1. Store pointers to myClass instances, so that once they are allocated, they never move in memory. Use std::unique_ptr<myClass>, not myClass*

2. Store sf::Font instances outside, so that they are not copied and moved around all the time by the vector. Using a resource manager usually helps.
Laurent Gomila - SFML developer

AlexBratosin

  • Newbie
  • *
  • Posts: 2
    • View Profile
Re: sf::Text::Font pointers reset to NULL
« Reply #2 on: August 22, 2017, 02:16:24 pm »
Thanks for replying Laurent!
That cleared it up.

 

anything