使用SFML绘制文本时的Segfault [英] Segfault when drawing text with SFML

查看:446
本文介绍了使用SFML绘制文本时的Segfault的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个 Button 类,它应该绘制一些顶点和一个字符串到 RenderWindow 。以下是包含不相关内容的代码:(此处是完整代码)

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.

这是从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 ()

>

推荐答案

我想这是因为你不保存字体对象。

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

请参阅文档


重要的是注意,sf :: Text实例不复制它使用的字体,它只保留对它的引用。因此,sf :: Font不能被破坏,而是由sf :: Text(即从不写一个使用本地sf :: Font实例创建文本的函数)。

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).

这篇关于使用SFML绘制文本时的Segfault的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆