Segfault when drawing text with SFML

2019-07-09 15:35发布

问题:

I have made a Button class that should draw some vertices and a string to a RenderWindow. Here's the code with irrelevant pieces snipped out: (here is the full code)

namespace game {

class Button
{
public:
    Button(int _x, int _y, int _width, int _height, std::string text)
    {
        ...

        sf::Font font;
        font.loadFromFile("res/SF Intermosaic B.ttf");
        label.setFont(font);
        label.setString(text);
        label.setCharacterSize(16);
        label.setColor(sf::Color(20, 20, 20));

        ...
    }

    ...

    void draw(sf::RenderWindow& window) const
    {
        sf::RenderStates states;
        states.texture = &texture;

        window.draw(vertices[state], states);
        window.draw(label); // If this line is commented out, there's no error.
    }

private:
    ...

    sf::Text label;

    ...
};

}

But when I draw the text, the program compiles just fine, but when I run it, it instantly crashes.

Here is the backtrace from gdb:

#0  0x00007ffff7bad604 in sf::Font::getTexture(unsigned int) const () from /usr/local/lib/libsfml-graphics.so.2
#1  0x00007ffff7bcd626 in sf::Text::draw(sf::RenderTarget&, sf::RenderStates) const () from /usr/local/lib/libsfml-graphics.so.2
#2  0x00007ffff7bc5bf4 in sf::RenderTarget::draw(sf::Drawable const&, sf::RenderStates const&) () from /usr/local/lib/libsfml-graphics.so.2
#3  0x00000000004033ad in game::Button::draw(sf::RenderWindow&) const ()
#4  0x0000000000403b64 in game::Menu::draw(sf::RenderWindow&) const ()
#5  0x00000000004042c5 in game::State::draw() ()
#6  0x0000000000402b4d in main ()

How would I solve this?

回答1:

I guess it's because you don't keep the font object alive.

See documentation :

It is important to note that the sf::Text instance doesn't copy the font that it uses, it only keeps a reference to it. Thus, a sf::Font must not be destructed while it is used by a sf::Text (i.e. never write a function that uses a local sf::Font instance for creating a text).



标签: c++ sfml