Solution
最终通过大量的试验和错误找到了答案,因此将在这里解释解决方案。
这是正确的语法:
// 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
解释
当我们添加 unique_ptr 作为数据成员时,我们需要给出类型SDL_Window
和“删除函数格式/语法”,因为普通delete
调用不正确。我们用decltype
从删除器函数自动构造正确的删除器格式。 (也许不是最准确的解释。)在某种程度上,decltype
有点像汽车...
std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> _window_;
该对象必须被初始化。我们在构造函数中执行此操作。我们将指针设置为nullptr
(因为我们不想在初始化SDL2之前初始化它)并且我们还设置了删除器函数。
: _window_(nullptr, SDL_DestroyWindow)
初始化 SDL 后,我们要创建一个窗口。通过调用智能指针最容易完成此操作reset()
功能。我们向它传递一个由创建窗口的函数返回的新指针。
_window_.reset(SDL_CreateWindow(...));
完毕。花了很长时间才弄清楚,但现在有意义了。参考
http://en.cppreference.com/w/cpp/memory/unique_ptr http://en.cppreference.com/w/cpp/memory/unique_ptr
为什么我的 unique_ptr 认为有一个空函数指针删除器? https://stackoverflow.com/questions/22915631/why-does-my-unique-ptr-think-is-has-a-null-function-pointer-deleter
unique_ptr 的初始化有什么问题? https://stackoverflow.com/questions/28853309/whats-wrong-with-this-initialization-of-unique-ptr