Smart pointers with SDL

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

 SDL_DestroyTexture(texture); 

or should I add a custom debugger when I create unique_ptr or shared_ptr , and if so, how can I do this using SDL types?

+7
c ++ c ++ 11 unique-ptr sdl sdl-2
source share
1 answer

You can create a functor with several overloaded implementations of operator() , each of which calls the correct destruction function for the corresponding type of argument.

 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 deleter in unique_ptr , and you could write wrapper functions, if you want, create unique_ptr s

 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()); } 
+23
source share

All Articles