Shared pointers causing weird behaviour

Posted by Setzer22 on Game Development See other posts from Game Development or by Setzer22
Published on 2014-06-06T21:34:49Z Indexed on 2014/06/06 21:55 UTC
Read the original article Hit count: 161

Filed under:
|

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...

© Game Development or respective owner

Related posts about c++

Related posts about sfml