是否可以将 SDL2 与智能指针一起使用?

use*_*501 4 c++ sdl smart-pointers unique-ptr sdl-2

我有这行代码

//std::unique_ptr<SDL_Window> _window_; // this is somewhere else...
_window_ = std::make_unique<SDL_Window>(SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, _WIDTH_, _HEIGHT_, SDL_WINDOW_SHOWN));
Run Code Online (Sandbox Code Playgroud)

它产生以下编译器错误

In file included from /usr/include/c++/6/memory:81:0,
                 from /home/user/prj/src/main.cpp:4:
/usr/include/c++/6/bits/unique_ptr.h: In instantiation of ‘typename 
std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = SDL_Window; _Args = {SDL_Window*}; typename 
std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<SDL_Window>]’:
/home/user/prj/src/main.cpp:36:170:   required from here
/usr/include/c++/6/bits/unique_ptr.h:791:30: error: invalid use of incomplete type ‘struct SDL_Window’
     { return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
Run Code Online (Sandbox Code Playgroud)

为什么?(它在没有智能指针的情况下工作正常,所以我的猜测是我不理解语法,这很容易修复。将添加源代码和CMakeLists.txt下面。)

CMakeLists.txt

cmake_minimum_required(VERSION 3.7)
project(prj)

find_package(SDL2 REQUIRED)
include_directories(prj ${SDL2_INCLUDE_DIRS})

add_executable(prj main.cpp)
target_link_libraries(prj ${SDL2_LIBRARIES})
Run Code Online (Sandbox Code Playgroud)

主程序

#include "SDL.h"
#include <memory>
#include <iostream>
#include <fstream>
#include <cstdint>

class Window
{

    public:

    Window()
        : _window_{nullptr}
        , _surface_{nullptr}
    {
        if(SDL_Init(SDL_INIT_VIDEO) < 0)
        {
            std::cerr << SDL_GetError() << std::endl;
        }
        else
        {
            _window_ = std::make_unique<SDL_Window>(SDL_CreateWindow("SDL Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, _WIDTH_, _HEIGHT_, SDL_WINDOW_SHOWN));

            if(_window_ == nullptr)
            {
                std::cerr << SDL_GetError() << std::endl;
            }
            else
            {
                _surface_ = std::make_unique<SDL_Surface>(SDL_GetWindowSurface(_window_.get()));
                SDL_FillRect(_surface_.get(), nullptr, SDL_MapRGB(_surface_->format, 0xFF, 0xFF, 0xFF));
                SDL_UpdateWindowSurface(_window_.get());
                SDL_Delay(1000);
            }
        }
    }

    ~Window()
    {
        SDL_DestroyWindow(_window_.get());
        SDL_Quit();
    }

    private:

    const int32_t _WIDTH_{600};
    const int32_t _HEIGHT_{400};

    std::unique_ptr<SDL_Window> _window_;
    std::unique_ptr<SDL_Surface> _surface_;

};


int main(int argc, char* argv[])
{
    Window window;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

use*_*501 9

解决方案

终于通过大量的试验和错误找到了答案,所以将在这里解释解决方案。

这是正确的语法:

// 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
Run Code Online (Sandbox Code Playgroud)

解释

当我们添加 unique_ptr 作为数据成员时,我们需要同时给出类型SDL_Window和“删除函数格式/语法”,因为普通delete调用是不正确的。我们使用decltype删除器函数自动构造正确的删除器格式。(也许不是最准确的解释。)在某种程度上,decltype有点像 auto...

std::unique_ptr<SDL_Window, decltype(&SDL_DestroyWindow)> _window_;
Run Code Online (Sandbox Code Playgroud)

这个对象必须被初始化。我们在构造函数中执行此操作。我们将指针设置为nullptr(因为我们不想在初始化 SDL2 之前对其进行初始化)并且我们还设置了删除器函数。

: _window_(nullptr, SDL_DestroyWindow)
Run Code Online (Sandbox Code Playgroud)

初始化 SDL 后,我们要创建一个窗口。这可以通过调用智能指针reset()函数轻松完成。我们向它传递一个由创建窗口的函数返回的新指针。

_window_.reset(SDL_CreateWindow(...));
Run Code Online (Sandbox Code Playgroud)

完毕。花了很长时间才弄明白,但现在是有道理的。参考

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

为什么我的 unique_ptr 认为它有一个空函数指针删除器?

这个unique_ptr 的初始化有什么问题?