This is a single-instance template class
#pragmaOnceTemplate<typename t>classcsingletont{ Public: StaticS MInstance () {returnM_pobj; } classCdeconstructor { Public: Cdeconstructor () {if(NULL = =m_pobj) {M_pobj=NewT (); } } ~Cdeconstructor () {if(csingletont::m_pobj) {DeleteCsingletont::m_pobj; Csingletont::m_pobj=NULL; } } };protected: Csingletont (void){} Virtual~csingletont (void){}protected: StaticS MM_pobj; Staticcdeconstructor M_dec;};
Inherit this template when you use it, such as:
#pragmaOnce#include"WebRef.h"#include"SingletonT.h"usingService1::CService1;classCwebaccess: Public csingletont<cwebaccess>{friendclassCsingletont<cwebaccess>; FriendclassCsingletont<cwebaccess>:: cdeconstructor; Public: CService1*GetService (); voidSetserviceurl (Constcstring&strURL);protected: CService1 m_service; Virtual~cwebaccess (void) {} cwebaccess (void){}}; Csingletont<cwebaccess>::cdeconstructor csingletont<cwebaccess>:: M_dec; Cwebaccess* Csingletont<cwebaccess>::m_pobj = NULL;
Two static for the template class to define, the header file is just a declaration. Since M_dec is a static member, it is constructed before the main function executes, and the main exits after the destructor, so this feature is used to create a singleton instance variable so that thread safety can be implemented without locking. A good structure is that the main function does not have multiple threads before main.
Single-Instance mode implementation