Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared_ptr custom deleter

I need to do custom deleter for shared_ptr. I know that this can be done in a similar way:

std::shared_ptr<SDL_Surface>(Surf_return_f(), MyDeleter);

But I would like to make them in the style of my custom deleter for unique_ptr:

struct SDL_Surface_Deleter {
    void operator()(SDL_Surface* surface) {
        SDL_FreeSurface(surface);
    }
};

using SDL_Surface_ptr = std::unique_ptr<SDL_Surface, SDL_Surface_Deleter>;

Is there any way to do this?

like image 836
Gogogo Avatar asked Dec 11 '25 13:12

Gogogo


1 Answers

It seems that you're trying to define a type alias that means "std::shared_ptr with my deleter type". There's no such thing, because std::shared_ptr has a type-erased deleter (the deleter is not part of the type).

Instead, you could create a custom version of make_shared:

template <class... Args>
std::shared_ptr<SDL_Surface> make_sdl_surface(Args&&... args) {
    return std::shared_ptr<SDL_Surface>(new SDL_Surface(std::forward<Args>(args)...),
                                        SDL_Surface_Deleter{});
}
like image 185
Brian Bi Avatar answered Dec 14 '25 04:12

Brian Bi