Smart pointers with SDL

后端 未结 1 873
星月不相逢
星月不相逢 2020-12-05 06:09

For my game should I use a raw pointer to create SDL_Window, SDL_Renderer, SDL_Texture etc. as they have specific delete functions

相关标签:
1条回答
  • 2020-12-05 06:09

    You could create a functor that has several overloaded operator() implementations, each of which call the correct destroy function for the respective argument type.

    struct sdl_deleter
    {
      void operator()(SDL_Window *p) const { SDL_DestroyWindow(p); }
      void operator()(SDL_Renderer *p) const { SDL_DestroyRenderer(p); }
      void operator()(SDL_Texture *p) const { SDL_DestroyTexture(p); }
    };
    

    Pass this as the deleter to a unique_ptr, and you could write wrapper functions if you wanted to, to create the unique_ptrs

    unique_ptr<SDL_Window, sdl_deleter>
    create_window(char const *title, int x, int y, int w, int h, Uint32 flags)
    {
        return unique_ptr<SDL_Window, sdl_deleter>(
                 SDL_CreateWindow(title, x, y, w, h, flags), 
                 sdl_deleter());
    }
    
    0 讨论(0)
提交回复
热议问题