Search code examples
c++pointersc++11stdshared-ptr

Assigning std::shared_ptr


In my code, I had ordinary pointer that was dynamically allocated

class Texture
{
    //code...
    SDL_Texture* m_texture;
};

I had Init() function from Texture class allocated SDL_Texture*, and destructor released memory.

However, this turned out to be a problem. I had to use shared_ptr, because I was using same texture for different objects, which would be destroyed, and thus disallowing me to display them properly(after first object from vector is destroyed, the texture(which is shared for all objects of same type) is gone).

So I decided to use shared_ptr, but I have one problem with it - I don't know how to assign something to shared_ptr's :

//Old code:
m_texture = loadTexture();

//New code:

class Texture
{
   std::shared_ptr<SDL_Texture> m_texture;
};
//code...

m_texture = loadTexture(); // Error! No assignment operator

I tried .get() function, but it's rvalue, so I can't assign anything to it. Any ideas?

Thanks in advance.


Solution

  • You need a custom deleter, too:

    #include <memory>
    
    // Fake SDL library
    
    typedef void SDL_Texture;
    
    SDL_Texture* SDL_CreateTextureFromSurface(/*SDL_Renderer* , SDL_Surface* */) {
        return 0;
    }
    
    void SDL_DestroyTexture(SDL_Texture* texture)
    {}
    
    // Shared
    
    typedef std::shared_ptr<SDL_Texture> SharedTexture;
    
    inline SharedTexture make_shared(SDL_Texture* texture) {
        return SharedTexture(texture, SDL_DestroyTexture);
    }
    
    int main() {
        SharedTexture texture;
        texture = make_shared(SDL_CreateTextureFromSurface());
    }
    

    Please be aware, a C library:

    • may use an opaque type
    • has it's own function for deletion or is using free