子系统的启动(Start-Up)和关闭(Shut-Down)

错误的方式一

wrong solution1
 1 class RenderManager
2 {
3 public:
4 RenderManager()
5 {
6 //start up the manager...
7 }
8 ~RenderManager()
9 {
10 //shut down the manager...
11 }
12 //...
13 };
14
15 //singleton instance
16 static RenderManager gRenderManager;

 错误原因:全局变量在函数入口点调用之间就构造好了,但是这些构造函数的调用顺序不确定。同样的,析构函数的调用顺序也不确定。

 

错误的方式2

wrong solution2
 1 class RenderManager
2 {
3 public:
4 //Get the one and only instance
5 static RenderManger* get()
6 {
7 //This function-static will be constructed on the first call to
8 //this function
9 static RenderManager sSingleton;
10 return sSingletion;
11 }
12 RenderManager()
13 {
14 //start up other manager we depend on,by calling their
15 //get() function first...
16 VideoManager::get();
17 TextureManager::get();
18 //now start up the render manager.
19 //...
20 }
21 ~RenderManager()
22 {
23 //shut down the manager.
24 //...
25 }
26 };

 

错误的原因:函数中定义的静态变量只会在函数第一次调用时候构建。但是这种方式不能够控制析构的顺序。

 

正确的方式

right solution
 1 class RenderManager
2 {
3 RenderManger()
4 {
5 //do nothing
6 }
7 ~RenderManager
8 {
9 //do nothing
10 }
11
12 void StartUp()
13 {
14 //start up the manager
15 }
16 void ShutDown()
17 {
18 //shut down the manager
19 }
20 //...
21 };
22
23 class PhysicsManager {/*similar*/};
24 class AnimationManager {/*similar*/};
25 class MemoryManager {/*similar*/};
26 class FileSystemManager {/*similar*/};
27
28 RenderManager gRM;
29 PhysicsManager gPM;
30 AnimationManager gAM;
31 MemoryManager gMM;
32 FileSystemManager gFSM;
33
34 int main()
35 {
36 //start up engine systems in the correct order
37 gMM.StartUp();
38 gFSM.StartUp();
39 gRM.StartUp();
40 gAM.StartUp();
41 gPM.StartUp();
42 //...
43
44 //Run the game
45 gSimulationManager.Run();
46
47 //shut everything down,in reverse order
48 //...
49
50 return 0;
51 }

 

posted @ 2012-02-28 09:09  Cavia  阅读(430)  评论(0编辑  收藏  举报