SFML Sprite loading

Jul 30, 2013 at 8:26pm
OK, I'm not having a problem per se, but something is going on in my code I can't explain. I'm writing a simple game engine with SFML and Box2D, and in my gameloop I have this line of code:

1
2
3
4
sf::Sprite Sprite;
Sprite.setTexture(textureManager.get(1));
...
window.draw(Sprite);


Now, when I run this, nothing is displayed. However, if I change it to this:

1
2
3
sf::Sprite Sprite;
Sprite.setTexture(textureManager.get(1));
sf::Texture tex = textureManager.get(1); //I originally just added this to print out size-info to the console 


it does draw! Anyone know what's going on here? TextureManager is just a class with a vector for storing textures, and the get function simply does return textures.at(i);
Last edited on Jul 30, 2013 at 8:36pm
Jul 30, 2013 at 10:09pm
is textureManager.get() returning a reference to a texture? Or a copy of one? If it returns a copy, the texture is deleted before the sprite can be drawn -- sf::Sprite does not store textures; it stores addresses to textures.
Jul 31, 2013 at 12:07am
Thanks:) Its returning a reference:

1
2
3
sf::Texture TextureManager::get(int i) {
	return textures.at(i);
}


Either way, I can't understand why just getting the texture once more without doing anything more with it would cause the sprite to draw...
Jul 31, 2013 at 12:14am
That's not returning a reference.
This is returning a reference:
1
2
3
sf::Texture &TextureManager::get(int i) {
    return textures.at(i);
}


EDIT:
I can't explain why the texture is drawing in the second version of your code either. If everything is as you describe then it shouldn't be. Maybe someone else could shed some light on that.
Last edited on Jul 31, 2013 at 12:17am
Jul 31, 2013 at 12:25am
Ooops, yes, I meant its not returning a pointer, haha :P
Last edited on Jul 31, 2013 at 12:29am
Jul 31, 2013 at 4:40am
1
2
3
sf::Sprite Sprite;
Sprite.setTexture(textureManager.get(1));
sf::Texture tex = textureManager.get(1); //I originally just added this to print out size-info to the console  


I suspect tex occupies the same position in memory that the temp returned by the first textureManager.get(1) did before it was destroyed, and the code works by happenstance.
Jul 31, 2013 at 12:52pm
Changing it so that it returns a reference fixed the problem tho, I no longer need that second line for it to draw:) Thanks!

EDIT: Also, when I made this change the framerate went through the roof:P
Last edited on Jul 31, 2013 at 12:53pm
Jul 31, 2013 at 3:16pm
@cire
I figured that was the case. I just thought it a bit unusual for the two textures to occupy the same space, even by happenstance.

@fafner
The framerate would go through the roof; copying textures around takes a lot of time. Copying addresses around doesn't. :p
Aug 1, 2013 at 1:09am
Thanks guys:) It's a bit embarrassing how little I know about memory-management stuff like this in C++, considering how long I've been using it :P
Topic archived. No new replies allowed.