Couple of questions about SDL_Window and unique_ptr

前端 未结 2 1160
灰色年华
灰色年华 2021-01-13 00:20

I currently had a problem with storing a SDL_Window pointer as a std::unique_ptr.
What I tried was:

std::unique_ptr window_;

相关标签:
2条回答
  • 2021-01-13 00:57

    I find this cleaner:

        auto window = std::unique_ptr<SDL_Window, std::function<void(SDL_Window *)>>(
                SDL_CreateWindow("Test", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, kWindowWidth, kWindowHeight, 0),
                SDL_DestroyWindow
        );
    
    0 讨论(0)
  • 2021-01-13 01:16

    The SDL_Window type is, just like the compiler says, incomplete.

    The SDL library is using a common pattern in C language: pointers to incomplete type.

    At the point you create the unique pointer, the SDL_Window type looks to the compiler like this:

    struct SDL_Window;
    

    That's one way you can create an incomplete type.

    The compiler doesn't know anything except that SDL_Window is a type, and not a global variable or a function. This also means it cannot assume what size it has, it cannot assume that it has any constructors or a destructor.

    As for the unique pointer to the SDL_Window, another way is to use this:

    struct SDLWindowDestroyer
    {
        void operator()(SDL_Window* w) const
        {
            SDL_DestroyWindow(w);
        }
    };
    
    std::unique_ptr<SDL_Window, SDLWindowDestroyer> window_;
    

    Now you don't need to provide a function in a constructor to the window_

    0 讨论(0)
提交回复
热议问题