关于 SDL_Window 和 unique_ptr 的几个问题 [英] Couple of questions about SDL_Window and unique_ptr
问题描述
我目前在将 SDL_Window 指针存储为 std::unique_ptr 时遇到问题.
我尝试的是:
I currently had a problem with storing a SDL_Window pointer as a std::unique_ptr.
What I tried was:
std::unique_ptr<SDL_Window> window_;
解决办法:
std::unique_ptr<SDL_Window, void(*)(SDL_Window*)> window_;
第一次尝试在内存头中不断抛出错误,说 SDL_Window 是一个不完整的类型.好吧,我知道 SDL_Window 是一个结构体,不能用
The first attempt kept throwing errors in the memory header, saying SDL_Window is an incomplete type. Well I know that SDL_Window is a struct and can't be instanciated with
SDL_Window* window_ = new SDL_Window();
因此实例化是通过 SDL_CreateWindow(params) 完成的.
therefore the instanciation is done with SDL_CreateWindow(params).
问题是:
- 为什么我不能为 SDL_Window 调用默认构造函数(或任何其他构造函数)?
为什么在这种情况下 unique_ptr 需要删除器,但在这里不需要:
- Why can't I call the default constructor (or any other) for SDL_Window?
Why does the unique_ptr needs a deleter in this case, but not here:
renderSystem_ = std::unique_ptr<Renderer::RenderSystem>(new Renderer::RenderSystem());
RenderSystem 是一个只有默认构造函数和析构函数的类.
是不是因为unique_ptr可以访问析构函数,它充当deleter,不需要作为模板参数进来?
RenderSystem being a class with just a default constructor, destructor.
Is it because the unique_ptr can access the destructor, which acts as the deleter and doesn't need to come as a template argument?
提前致谢!
推荐答案
SDL_Window
类型,正如编译器所说,是不完整的.
The SDL_Window
type is, just like the compiler says, incomplete.
SDL 库使用 C 语言中的一种常见模式:指向不完整类型的指针.
The SDL library is using a common pattern in C language: pointers to incomplete type.
在创建唯一指针时,SDL_Window
类型在编译器中看起来像这样:
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.
除了SDL_Window
是一种类型,而不是全局变量或函数之外,编译器一无所知.这也意味着它不能假设它有多大,也不能假设它有任何构造函数或析构函数.
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.
至于SDL_Window
的唯一指针,另一种方法是使用这个:
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_;
现在您不需要在构造函数中为 window_
Now you don't need to provide a function in a constructor to the window_
这篇关于关于 SDL_Window 和 unique_ptr 的几个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!