Shared pointers causing weird behaviour
- by Setzer22
I have the following code in SFML 2.1
Class ResourceManager:
shared_ptr<Sprite> ResourceManager::getSprite(string name) {
shared_ptr<Texture> texture(new Texture);
if(!texture->loadFromFile(resPath+spritesPath+name))
throw new NotSuchFileException();
shared_ptr<Sprite> sprite(new Sprite(*texture));
return sprite;
}
Main method: (I'll omit most of the irrelevant code
shared_ptr<Sprite> sprite = ResourceManager::getSprite("sprite.png");
...
while(renderWindow.isOpen())
renderWindow.draw(*sprite);
Oddly enough this makes my sprite render completely white, but if I do this instead:
shared_ptr<Sprite> ResourceManager::getSprite(string name) {
Texture* texture = new Texture; // <------- From shared pointer to pointer
if(!texture->loadFromFile(resPath+spritesPath+name))
throw new NotSuchFileException();
shared_ptr<Sprite> sprite(new Sprite(*texture));
return sprite;
}
It works perfectly.
So what's happening here? I assumed the shared pointer would work just as a pointer. Could it be that it's getting deleted? My main method is keeping a reference to it so I don't really understand what's going on here :S
EDIT: I'm perfectly aware deleting the sprite won't delete the texture and this is generating a memory leak I'd have to handle, that's why I'm trying to use smart pointers on the first place...