c ++具有自定义删除器错误的唯一指针

c++ Unique pointer with custom deleter error

我正在尝试使用带有自定义删除器的唯一指针制作一个包装器 class。这是 class:

class WindowObj
{
    public:
        WindowObj();
        WindowObj(const WindowObj&) = delete;
        WindowObj& operator=(const WindowObj&) = delete;
        WindowObj(WindowObj&&);
        WindowObj& operator=(WindowObj&&);
        WindowObj(const char* title,int x,int y,const int& w,const int& h,SDL_WindowFlags flags);
        SDL_Window* get();
    protected:
    private:
    std::unique_ptr<SDL_Window,decltype(&SDL_DestroyWindow)> window;
};
WindowObj::WindowObj(const char* title,int x,int y,const int& w,const int& h,SDL_WindowFlags flags)
{
    window = make_resource(SDL_CreateWindow,SDL_DestroyWindow,title,x,y,w,h,flags);
}


SDL_Window* WindowObj::get(){
    return window.get();
}

WindowObj::WindowObj(){
    window = NULL;
}

WindowObj::WindowObj(WindowObj&& other){
    std::swap(window,other.window);
}

WindowObj& WindowObj::operator=(WindowObj&& other){
    std::swap(window,other.window);
}

问题是当我尝试编译它时出现错误 error: static assertion failed: constructed with null function pointer deleter。使用 shared_ptr 可以解决问题,但我可能不需要共享指针。有帮助吗?

您从未将 SDL_DestroyWindow 传递给 window(传递给 unique_ptr 本身,而不是其内容)。 尝试

WindowObj::WindowObj(const char* title,int x,int y,const int& w,const int& h,SDL_WindowFlags flags)
    : window(make_resource(SDL_CreateWindow,SDL_DestroyWindow,title,x,y,w,h,flags), &SDL_DestroyWindow) {}

您没有初始化 window,您是在它第一次被默认构造后分配给它(使用空删除器,因此出现错误)。

您需要使用成员初始化列表来实际初始化它:

WindowObj::WindowObj(const char* title,int x,int y,const int& w,const int& h,SDL_WindowFlags flags)
: window(make_resource(SDL_CreateWindow,SDL_DestroyWindow,title,x,y,w,h,flags))
{
}

(假设 make_resource returns a unique_ptr 并将第二个参数传递给其构造函数。)