0

I have a class where I try to create static unique_ptr to the SDL_Renderer:

.h

   class Game
    {
    public:
        
        static std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer*)>> Renderer;
    
        // ...
    };

.cpp

    std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer*)>> Game::Renderer;

    void Game::Initialize(int width, int height)
    {   
        // Some code here //

        // Initialization OPTION 1
        Renderer = std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer*)>>
                        (SDL_CreateRenderer(Window.get(), -1, 0), SDL_DestroyRenderer);
        
        return;
    }

Questions are:

  1. Is it the right way to initialize the unique_ptr here? (at a glance code works as expected)
  2. Is it possible to use somehow make_unique instead?
  3. Will the smart pointer work correctly and call SDL_DestroyRenderer after Game deletion?
  4. Is it safe and corresponds to the best practices to use smart-pointers with C-libs classes/structs?
Anton
  • 185
  • 1
  • 14

1 Answers1

1

What you are describing is called the singleton-pattern. The pattern is used when you want to create an instance of something you only need one instance of for the whole program in which the pattern is well accepted - I guess. So if you think that is true in your case, you are totally fine when using the pattern.

However, though your code looks ok, what I have seen most often looks more like that:

// h:
class Game
{
public:
    static SDL_Render& GetSDL_Render();
};

// cpp:
SDL_Render& Game::GetSDL_Render()
{
    static auto singleton = 
        std::unique_ptr<SDL_Renderer, std::function<void(SDL_Renderer*)>>
            (SDL_CreateRenderer(Window.get(), -1, 0), SDL_DestroyRenderer);
    return *singleton.get();
}

For more information see: C++ Singleton design pattern

JulianW
  • 897
  • 9
  • 23