14

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

SDL_DestroyTexture(texture); 

or should I add a custom deleter when I create a unique_ptr or shared_ptr and if so how would I do this with SDL types?

Praetorian
  • 106,671
  • 19
  • 240
  • 328
Dennis Harrop
  • 167
  • 1
  • 7
  • 1
    What does the last sentence mean - *how would I do this with SDL variables*? Are you asking how to go about creating a `unique_ptr` that'll automatically destroy some `SDL_*` object? – Praetorian Jun 16 '14 at 20:47
  • Sorry for bad english I should have read through it again. What I meant is how do I create a unique_ptr to handle a SDL_Window/Renderer/Texture etc.. because they all have different ways to be deleted. Or should I just use a raw pointer as it would not make much difference as I know where they should be deleted. – Dennis Harrop Jun 16 '14 at 20:50

1 Answers1

33

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());
}
Praetorian
  • 106,671
  • 19
  • 240
  • 328