0

I would like to write a simple game using SDL 2.0, and its structure looks kind of like this:

  • class Engine, which will initialize SDL(SDL.Init() ) in its constructor, call SDL_Quit() in destructor, and contain instances of Window and Texture
  • class Texture - wrapper class for SDL_Texture* . Creating texture when created, destroying texture in destructor
  • class Window - wrapper class for SDL_Window, creating SDL_Window* and SDL_Renderer* at beggining, deleting in destructor.

Now, from what I know, SDL_Quit() unloads dll, closes all subsystems, etc. If I understand correctly, then if I call SDL_Quit(), calling SDL_DestroyWindow(), SDL_DestroyRenderer() and SDL_DestroyTexture() may have no effect or cause bug, because systems have been unloaded as well as dll.

Therefore, I would like Texture and Window inside Engine to be destroyed in the beggining of Engine's destructor, before SDL_Quit() is called.

When I tried simulating it on a simple class example, I got simple LIFO response:

ClassOne object initialized

ClassTwo object initialized

Aggregate object initialized

Aggregate object destroyed

ClassTwo object destroyed

ClassOne object destroyed

And it isn't what I want. I managed to get solution to my problem using pointers and dynamic memory allocation. I simply create them using operator new in Aggregate's constructor, and destroy them, using operator delete in destructor.

But, is there other way to do it, not involving pointers? Thanks in advance.

4

2 回答 2

2

不涉及指针:

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

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

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

并且您想要一个与 outputInit 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;
};
于 2013-08-31T17:14:45.660 回答
1

如果您正确订购课程,您将获得所需的销毁顺序:

在课堂上:

class X {
   public:
   X()
   // This order is not relevant and should produce a compiler warning
   : ..., c(), b(), a()
   {}


   private:
   // The members are initialized in this order and destructed in the opposite order.
   A a;
   B b;
   C c
   ...
}

同样适用于单个(!)翻译单元中的静态实例:按定义相反的顺序构造和销毁。

如果您有多个翻译单元,则未指定每个单元的初始化顺序。在函数中包含静态数据,可以简化它 - 数据在第一个函数调用中初始化。

于 2013-08-31T16:56:07.000 回答