c++ - 如何指定析构函数调用的顺序?

标签 c++ sdl

我想使用 SDL 2.0 编写一个简单的游戏,其结构如下所示:

  • Engine 类,在其构造函数中初始化 SDL(SDL.Init() ),在析构函数中调用 SDL_Quit(),并包含 Window 和 Texture 的实例
  • Texture 类 - SDL_Texture* 的包装类。创建时创建纹理,在析构函数中销毁纹理
  • Window 类 - SDL_Window 的包装类,在开始时创建 SDL_Window* 和 SDL_Renderer*,在析构函数中删除。

现在,据我所知,SDL_Quit()卸载dll,关闭所有子系统等。如果我理解正确,那么如果我调用SDL_Quit(),调用SDL_DestroyWindow()、SDL_DestroyRenderer()和SDL_DestroyTexture()可能没有影响或导致错误,因为系统和 dll 都已卸载。

因此,我希望在调用 SDL_Quit() 之前,在 Engine 的析构函数开始时销毁 Engine 中的 Texture 和 Window。

当我尝试在一个简单的类示例上对其进行模拟时,我得到了简单的后进先出响应:

ClassOne object initialized

ClassTwo object initialized

Aggregate object initialized

Aggregate object destroyed

ClassTwo object destroyed

ClassOne object destroyed

这不是我想要的。我设法使用指针和动态内存分配解决了我的问题。我只是在 Aggregate 的构造函数中使用 operator new 创建它们,并在析构函数中使用 operator delete 销毁它们。

但是,有没有其他方法可以做到这一点,而不涉及指针? 提前致谢。

最佳答案

不涉及指针:

如果你有(假设 #include <iostream> )

class Window {
public:
    Window() { std::cout << "W "; }
    ~Window() { std::cout << "~W "; }
};

class Texture {
public:
    Texture() { std::cout << "T "; }
    ~Texture() { std::cout << "~T "; }
};

并且您想要一个对应于输出 Init W T 的订单和 ~T ~W Quit ,然后,而不是:

class Engine {
public:
    Engine() { std::cout << "Init "; }
    ~Engine() { std::cout << "Quit "; }
private:
    Window w;
    Texture t;
};

(执行 W T InitQuit ~T ~W ),执行此操作:

class Initializer {
public:
    Initializer() { std::cout << "Init "; }
    ~Initializer() { std::cout << "Quit "; }
};

class Engine {
public:
    Engine() { /* nothing */ }
    ~Engine() { /* nothing */ }
private:
    Initializer i;
    Window w;
    Texture t;
};

关于c++ - 如何指定析构函数调用的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18550290/

相关文章:

c++ - pthread 2 信号和槽包装器 mit QEventLoop

c++ - 如何使用 typedef 完全隐藏特定类型?

c++ - 将 LibRocket 与 SDL 和 OpenGL 集成

c++ - 如何在 cmake 中使用 SDL2 和 SDL_image

c# - 如何确定线程在哪个 CPU 上运行?

c++ - StringHashTable 线程安全中使用的静态函数?

C++ 回溯排列

c++ - glGetString(GL_VERSION) 返回 1.1.0,即使卡支持 2.1

c - SDL函数名称?

c++ - 来自库的不完整类型的 shared_ptr