通常singleton模式定义函数域内的静态成员,该静态成员的释放都是依赖系统回收进程时自动进行。这里提供的singleton类模板,使用_onexit的CRT扩展设定exe的winMain返回后或dll在卸载时的回调函数功能,实现该静态成员的有控制的释放。
初步设想,这种方式作用有:
1、可控制多个singleton类对象的释放顺序
以下是完整的类模板
// Basic implementation of a singleton which calls the destructor
// when the exe is shutting down or the DLL is being unloaded.
template <typename Derived>
class SingletonBase {
public:
static Derived* GetInstance() {
static Derived* instance = NULL;
if (NULL == instance) {
instance = new Derived();
// Microsoft CRT extension. In an exe this this called after
// winmain returns, in a dll is called in DLL_PROCESS_DETACH
_onexit(OnExit);
}
return instance;
}
private:
// this is the function that gets called by the CRT when the
// process is shutting down.
static int __cdecl OnExit() {
delete GetInstance();
return 0;
}
};