No appropriate default constructor available for std::unique_ptr

不羁岁月 提交于 2019-12-06 11:59:57

A std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> is not default constructable. That means in

cGraphics::cGraphics(int xWin, int yWin) ***
{
    m_Window = std::move(Create_Window(xWin, yWin));

    if (m_Window == nullptr)
    {
        throw "SDL_Window or SDL_Renderer not ready!";
    }
}

When you reach the part *** the compiler is going to try and default construct m_Window since you didn't do so in the member initialization list. That attempt from the compiler ro default construct m_Window is what causes the error. We can fix this by moving m_Window = std::move(Create_Window(xWin, yWin)); out of the constructor body and putting it in the member initialization list like

cGraphics::cGraphics(int xWin, int yWin) : m_Window(Create_Window(xWin, yWin))
{   
    if (m_Window == nullptr)
    {
        throw "SDL_Window or SDL_Renderer not ready!";
    }
}

If you don't want to do that then you can delegate to the default constructor and then assign to m_Window like you were doing originally. That would look like

cGraphics::cGraphics(int xWin, int yWin) : cGraphics()
{
    m_Window = Create_Window(xWin, yWin);

    if (m_Window == nullptr)
    {
        throw "SDL_Window or SDL_Renderer not ready!";
    }
}

Here is how you defined your unique_ptr:

std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> m_Window;

That means, it's constructor has to be called with an instance of the custome deleter, in your case, function SDL_DestroyWindow - remember, you told the pointer what is deleter's type, not what the actual deleter (a function pointer in your case).

To make this code work, you have to properly construct your pointer with a deleter instance, for example:

cGraphics::cGraphics(int xWin, int yWin) : 
                     m_Window{Create_Window(xWin, yWin)} {...}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!