SFML Sprite loading

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
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.
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...
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
Ooops, yes, I meant its not returning a pointer, haha :P
Last edited on
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.
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
@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
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.