猫猫哥

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
/* Initialization Fiasco
    一个会使程序崩溃的细微的问题
*/

// 不同文件的编译顺序是不确定的
// 如果一个文件依赖另一个文件的对象先初始化,可能出现问题

// 解决方法: Singleton
#include "Global.h"
#include "Dog.h"
#include "Cat.h"

Dog* Singleton::pd = 0;
Cat* Singleton::pc = 0;

Dog* Singleton::getDog() {
   if (!pd)
      return new Dog("Gunner");  //Initialize Upon First Usage Idiom
    return pd;
}

Cat* Singleton::getCat() {
   if (!pc)
      return new Cat("Smokey");
    return pc;
}

Singleton::~Global() {
    if (pd) delete pd;
    if (pc) delete pc;
    pd = 0;
    pc = 0;
}
posted on 2018-12-24 00:28  猫猫哥  阅读(193)  评论(0编辑  收藏  举报