Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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

share|improve this question
add comment

1 Answer

I may be way off here but I thought it was worth a try:

If the sprite class constructor takes a regular Texture * or a Texture reference (as opposed to it taking and storing a shared pointer) then when the shared_ptr goes out of scope in getSprite the texture will be destroyed (because no shared_ptr's to the texture exist after that point).

share|improve this answer
    
The constructor call (from the API documentation) is: sf::Sprite::Sprite(const Texture & texture) so it's doing a pass by reference. That would technically work the same as a pointer right? –  Setzer22 yesterday
    
Yeah. So when you leave getSprite, no shared_ptr<Texture> exists - so in the shared_ptr destructor it destroys the resource. See cplusplus.com/reference/memory/shared_ptr –  CiscoIPPhone yesterday
    
So the only way would be to keep the texture around somewhere. That gave me the idea of making a texture cache for the resource manager, may I ask if using shared_ptr would break an STL container like map? –  Setzer22 yesterday
    
No, it will not. –  Josh Petrie yesterday
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.