Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

c++ - Smart pointers with SDL

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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());
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...