Common mistakes

Oftentimes, new users of SFML attempt to do something like this:

sf::Sprite CreateSprite(std::string l_path){
    sf::Texture texture;
    texture.loadFromFile(l_path);
    . . .
    return sf::Sprite(texture);
}

When attempting to draw the returned sprite, a white square pops out where the sprite is supposed to be located. What happened? Well, take a look back at the section where we covered textures. The texture needs to be within scope as long as it's being used by a sprite because it stores a pointer to the texture instance. From the example above, we can see that it is statically allocated, so when the function returns, the texture that got allocated on the stack is now out of scope and gets popped. Poof. Gone. Now the sprite is pointing to ...

Get SFML Game Development By Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.