简体   繁体   English

SFML纹理持有人已删除,但仍在范围内

[英]SFML texture holder deleted although still in scope

So I'm new to SFML. 所以我是SFML的新手。 I read a lot of post, but I really don't get it. 我读了很多文章,但我确实听不懂。 I wrote an texture holder: 我写了一个纹理支架:

class tile_texture_holder {
private:
    sf::Texture tx;
public:
    tile_texture_holder(type a) {
        switch (a) {
        case type::desert:
            tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/desert.png");
            break;
        case type::grass:
            tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/grass.png");
            break;
        case type::mountain:
            tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/mountain.png");
            break;
        case type::water:
            tx.loadFromFile("C:/Users/Andreas/source/repos/conquer/Media/water.png");
            break;
        }
    }
    sf::Texture ret_texture() {
        return tx;
    }

    ~tile_texture_holder() {
        std::cout << "///////////////////////HOLDER DELETED!!!/////////////////////" << std::endl;
    }
};

And I tried to load a sprite with it in different ways.... 我试图以不同的方式加载精灵。

For example: 例如:

tile_texture_holder t(type::desert);
        sf::Sprite s; 
        s.setTexture(t.ret_texture());

(in the same function, where I draw the sprite) (在相同的函数中,我绘制精灵)

I always get the white box being drawn. 我总是画白框。 And I really dont get why the texture_holder is getting deleted. 而且我真的不明白为什么texture_holder被删除。

BTW type is an enum. BTW类型是一个枚举。

I hope somebody can help me solve my issue! 希望有人可以帮助我解决我的问题!

s.setTexture(t.ret_texture());

in the line above you have undefined behaviour. 在上面的行中,您的行为不确定。

ret_texture returns temporary texture (it is returned by value, so a copy is made), setTexture takes reference to it, then at the end of expression temporary texture is destroyed and you have dangling reference in s . ret_texture返回临时纹理(按值返回,因此会生成一个副本), setTexture进行引用,然后在表达式末尾销毁临时纹理,并且在s有悬挂的引用。

Why this happens? 为什么会这样? Because setTexture of Sprite only holds reference to texture, it doesn't copy it. 由于Sprite setTexture仅保留对纹理的引用,因此不会复制它。

According to SFML Sprite reference : 根据SFML Sprite参考

The texture argument refers to a texture that must exist as long as the sprite uses it. Texture参数是指只要精灵使用它就必须存在的纹理。 Indeed, the sprite doesn't store its own copy of the texture, but rather keeps a pointer to the one that you passed to this function. 实际上,精灵不会存储纹理的副本,而是保留指向您传递给该函数的指针的指针。

Solution: ret_texture should return texture by reference. 解决方案: ret_texture应该通过引用返回纹理。

sf::Texture& ret_texture() {
    return tx;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM