【发布时间】:2018-07-18 06:00:43
【问题描述】:
我有这行代码
//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));
它会产生以下编译器错误
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)...)); }
为什么? (没有智能指针它也能正常工作,所以我猜我不理解语法,这很容易解决。将在下面添加源代码和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})
main.cpp
#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;
}
【问题讨论】:
-
@lcs 已编辑问题
-
struct SDLWindowDestroyer { void operator()(SDL_Window* w) { SDL_DestroyWindow(w); } }; using SDLWindowPtr = std::unique_ptr<SDLWindow, SDLWindowDestroyer>; -
@user3728501 该问题的答案包含语法。
-
@lcs 他们使用不同的语法来使用结构。在这种情况下,我的问题变成“我的尝试有什么问题”。
标签: c++ sdl smart-pointers sdl-2 unique-ptr