Magnus
Magnus

Reputation: 514

c++ Unique pointer with custom deleter error

I am trying to make a wrapper class with an unique pointer with a custom deleter. This is the 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);
}

The problem is that when I try to compile this I get the error error: static assertion failed: constructed with null function pointer deleter. Using a shared_ptr instead fixes the problem, but I may not need sharing the pointer. Any help?

Upvotes: 2

Views: 1070

Answers (2)

Emil Laine
Emil Laine

Reputation: 42828

You aren't initializing window, you're assigning to it after it is first default-constructed (with a null deleter, hence the error).

You need to use the member initializer list to actually initialize it:

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))
{
}

(Assuming make_resource returns a unique_ptr and passes the 2nd argument to its constructor.)

Upvotes: 2

bipll
bipll

Reputation: 11940

You have never passed SDL_DestroyWindow to window (to the unique_ptr itself, not its contents). Try

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) {}

Upvotes: 1

Related Questions