Shared_ptr 自定义删除器

Gog*_*ogo 2 c++ sdl smart-pointers c++11

我需要为 shared_ptr 做自定义删除器。我知道这可以通过类似的方式完成:

std::shared_ptr<SDL_Surface>(Surf_return_f(), MyDeleter);
Run Code Online (Sandbox Code Playgroud)

但我想按照我的 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>;
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Kev*_*vin 8

与 a 不同unique_ptr, a 的删除器shared_ptr不是类型的一部分。您必须将删除器传递给 的构造函数shared_ptr

您可以将其包装在函数中:

std::shared_ptr<SDL_Surface> make_shared_surface(SDL_Surface* surface)
{
    return std::shared_ptr<SDL_Surface>(surface, MyDeleter);
}
Run Code Online (Sandbox Code Playgroud)

然后打电话make_shared_surface(Surf_return_f())


Bri*_*ian 6

您似乎正在尝试定义一个类型别名,表示“std::shared_ptr使用我的删除器类型”。没有这样的东西,因为std::shared_ptr有一个类型擦除的删除器(删除器不是类型的一部分)。

相反,您可以创建一个自定义版本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{});
}
Run Code Online (Sandbox Code Playgroud)