c++ - SDL 包装器 header 中的智能指针

标签 c++ sdl smart-pointers

SDL 类型如何作为成员用于包装类内部的智能指针? (使用 SDL2、mingw 和 gnu-make)

我知道这个问题对我来说并不简单,所以这里是当前工作的上下文:

主要.cpp:

#include "WindowWrapper.h"

int main(int argnum, char* argv[])
{
  //stuff...

  WindowWrapper myWindow;

  //more stuff...
}

WindowWrapper.h

//include guard...

class SDL_Window;

class WindowWrapper
{
  public:
    //constructor destructor, stuff....

  private:
    SDL_Window* window;
}

WindowWrapper.cpp

#include "WindowWrapper.h"
#include "SDL.h"

WindowWrapper::WindowWrapper()
{
  int initResult = SDL_Init(SDL_INIT_VIDEO);
  //error check, boring stuff...

  window = SDL_CreateWindow(/* whatever, params... you know... */)
}

WindowWrapper::~WindowWrapper()
{
  SDL_DestroyWindow(window);
  window = nullptr;

  SDL_Quit();
}

所以正如我所说,这工作正常,但我想将指针(如窗口(表面、渲染器、纹理,通常))更改为智能指针,如 std::unique_ptr 或类似的指针。

可是…… 给定一个像这样的自定义删除器:

struct CustomDeleter
{
  void operator()(SDL_Window* window)
  {
    SDL_DestroyWindow(window);
  }

  void operator()(SDL_Window** window) //sounds crazy, but you would try even crazier stuff when experimenting
  {
    SDL_DestroyWindow(*window);
  }
};

我因以下所有问题而失败(全部针对 WindowWrapper.h):

#incldue "SDL.h"  //--> Fails to include in any header,
// causes the famous "Undefined Reference to WinMain" problem

/*
 * Whatever definitions
 */


#include <memory>

typedef struct SDL_Window SDL_Window;
class WindowWrapper
{
 /*
  * Stuff
  */
 private:
   std::unique_ptr<SDL_Window, CustomDeleter> window;  //--> obviously fails, incomplete type 
}


#include <memory>

class SDL_Window;
class WindowWrapper
{
 /*
  * Stuff
  */
 private:
   std::unique_ptr<SDL_Window*, CustomDeleter> window;  //--> acts like SDL_Window**... 
   //compiles, but almost impossible to get it work without extra intermediate objects, and other nasty hacks
}

我还尝试制作一个自定义指针模板类,它将 SDL_Whatever* 和删除函数作为构造参数,在我想复制/移动包装器对象(比如将它们存储在 map 或其他容器中)之前它很好).那时所有的复制/移动语义都变得非常困惑,实现像 shared_ptr 这样的引用计数器现在对我来说已经超出了范围,无论如何,这就是实现 std 智能指针的原因。

总结一下:

  1. 有什么方法可以在 header 中包含 SDL 类型本身吗? 我猜头文件中包含 SDL.h 时失败的原因是因为与 cpp 文件不同,头文件在编译期间没有链接在一起,所以它永远找不到 main 函数的定义。但是,如果只包含类型(尽管它们在 SDL 包中没有自己的包含文件 -.-"),则可以很容易地解决这个问题。

  2. 是否有一种干净的方法来绕过智能指针的“您只能声明原始指针和没有完整类型的引用”规则? 我知道唯一指针有一个异常(exception),如果你能保证关于析构函数的一堆东西,但我认为像这样定义的自定义删除器实际上违反了这些规则。但我仍然认为智能指针应该有办法解决这个问题,因为它们实际上是带有附加功能的指针。我就是找不到怎么做。

最佳答案

您可以让它与您的自定义删除器一起正常工作:https://wandbox.org/permlink/K3L7BvJSf7OuKfFM

关键是您在 header 中声明删除器operator() 以及包装器,但在关联的实现其功能.cpp。这样它就是一个完整的类型,但您仍将所有实际功能封装在包装器 .cpp 中,您可以在其中访问实际的 SDL。

关于c++ - SDL 包装器 header 中的智能指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50990404/

相关文章:

c++ - GL_UNSIGNED_SHORT_5_6_5 未声明?

c++ - 在现代 C++ 中使用原始指针是不好的做法吗?

c++ - 如何让它工作,2个类(class)的问题

textures - 如何将两个 SDL2 纹理混合为一个纹理?

c++ - 使用 VS 的 SDL 2.0 构建错误

c++ - 通过非智能指针参数将智能指针传递给函数

c++ - 任何人都知道有什么计划让 ^ 成为 shared_ptr<T> 的简写吗?

c++ - 调试器已附加 - cscript

c++ - 显式模板特化问题

c++ - 如何从理论上计算嵌套循环的运行时间?