Typedef a shared_ptr type with a static custom deleter, similar to unique_ptr

后端 未结 2 966
萌比男神i
萌比男神i 2020-12-19 19:26

I have read through many questions on SO on custom deleter for shared_ptr and unique_ptr, and the difference between the two. But, I still haven\'t

2条回答
  •  眼角桃花
    2020-12-19 19:50

    A typedef is a static, compile-time feature.

    A deleter passed to a shared_ptr is a dynamic, run-time property. The deleter is "type-erased" and is not part of the shared_ptr interface.

    Therefore you can't declare a typedef to represent an alternative deleter, you just pass one to the constructor.

    What would be the best way to achieve the same kind of usage as with the unique_ptr example of above.

    You could use functions to create the resources and return them in a shared_ptr

    shared_ptr create_sdl_surface(const char* s)
    {
      return shared_ptr(IMG_load(s), SDL_FreeSurface);
    }
    

    But I would have those functions return a unique_ptr instead, which can be converted to shared_ptr, as below.

    I would get rid of the macro and do something like this:

    // type with overloaded functions for freeing each resource type
    struct SDL_deleter
    {
      void operator()(SDL_Surface* p) const { if (p) SDL_FreeSurface(p); }
      void operator()(SDL_RWops* p) const { if (p) SDL_RWclose(p); }
      // etc.
    };
    
    // a unique_ptr using SDL_deleter:
    template
      using SDL_Ptr = std::unique_ptr;
    
    // typedefs for the common ptr types:
    using SurfacePtr = SDL_ptr;
    using RWopsPtr = SDL_ptr;
    // etc.
    

    To answer the shared_ptr part of your question, define functions that create resources and return them in a SDL_ptr:

    SurfacePtr createSurface(const char* s) { return SurfacePtr(IMG_load(s)); }
    RWopsPtr createRWops([...]) { return RWopsPtr([...]); }
    // etc.
    

    Then you can easily create a shared_ptr from the result of those functions:

    shared_ptr s = createSurface("image.png");
    

    The shared_ptr automatically acquires the right deleter from the unique_ptr.

提交回复
热议问题