Is it possible to use SDL2 with smart pointers?

[亡魂溺海] 提交于 2019-12-05 21:22:23

Solution

Finally figured out the answer with a lot of trial and error, so will explain the solution here.

This is the correct syntax:

// first define the unique_ptr as member of class
std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> _window_;

// second, initialize in the member initialization list of class constructor
// probably don't need to do this if not embedding as member of class
class_name()
    : _window_(nullptr, SDL_DestroyWindow)
{
    // blaa blaa SDL code etc
    _window_.reset(SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WIDTH, HEIGHT, SDL_WINDOW_SHOWN));
}

// finally we need to be able to delete
// but this is handled automatically

Explanation

When we add the unique_ptr as a data member, we need to give both the type SDL_Window and the "deleter function format / syntax", becuase an ordinary delete call is not correct. We use decltype to automatically construct the correct deleter format from the deleter function. (Perhaps not the most accurate explanation.) In a way, decltype is somewhat like auto...

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

This object must be initialized. We do this in the constructor. We set the pointer to nullptr (because we do not want to initialize it before initializing SDL2) and we also set the deleter function.

: _window_(nullptr, SDL_DestroyWindow)

After initializing SDL, we then want to create a window. This is done most easily by calling the smart pointer reset() function. We pass it a new pointer returned by the function which creates the window.

_window_.reset(SDL_CreateWindow(...));

Done. Took a long time to figure out but makes sense now. References

http://en.cppreference.com/w/cpp/memory/unique_ptr

Why does my unique_ptr think is has a null function pointer deleter?

What's wrong with this initialization of unique_ptr?

Those structures are opaque data structures, you don't have the full definition of them. That means, among other things, that the default std::unique_ptr deleter don't know how to "delete" the structures.

You need to provide your own custom deleter. For SDL_Window it's the SDL_DestroyWindow function.

A SDL Windows is destroyed using SDL_DestroyWindow, not plain delete, like the unique_ptr's default deleter does. You need to supply a custom deleter to unique_ptr, which will call SDL_DestroyWindow.

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