C++进阶--静态初始化的惨败

/* 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;
}
原文地址:https://www.cnblogs.com/logchen/p/10166576.html