Singleton mode is a C + + syntax essence condensed one embodiment, there is an old saying: "Perfectly formed!" To describe a single case is very appropriate!
The following code analyzes if you are malloc and memcpy a single pointer can be a major hazard and how to prevent this from happening.
1#include <iostream>2#include <cassert>3#include <cstdlib>4#include <cstring>5 6 usingstd::cout;7 usingStd::endl;8 9 structSingleton;Ten Staticsingleton* Inst =NULL; One structSingleton { A Virtual voidTest_what () { - if( This==Inst) { -cout <<"OK, it ' s mine."<<Endl; the}Else { -cout <<"You go the wrong door"<<Endl; -Assertfalse); - } + } - + voidWhat () { A if( This==Inst) { atcout <<"OK, it ' s mine."<<Endl; -}Else { -cout <<"You go the wrong door"<<Endl; -Assertfalse); - } - } in - voidSelf () { to if( This==Inst) { +cout <<"OK, it ' s mine."<<Endl; -}Else { thecout <<"WTF!!!"<<Endl; *Assertfalse); $ }Panax Notoginseng } - the Staticsingleton*getinstance () { + if(NULL = =Inst) AInst =NewSingleton; the returnInst; + } - $ Static voiddestroyinstance () { $ if(NULL! =Inst) { - DeleteInst; -Inst =NULL; the } - }Wuyi Private: the Singleton () {} -Singleton (Constsingleton&); Wusingleton&operator=(Constsingleton&); - }; About $ - intMainintargcChar*argv[]) - { - //Initialize at the beginning of the program to avoid the initialization of multiple threads ASingleton *a =singleton::getinstance (); +Singleton *p = (singleton*)malloc(sizeof(Singleton)); the -memcpy (P, a,sizeof(Singleton)); $ the //p->self (); the //p->what (); theP->test_what (); theA->what (); - in Free(p); the Singleton::d estroyinstance (); the About return 0; the}
Summarize:
1, the above single example is a more common implementation
2, memcpy will destroy the uniqueness of the singleton
3, memcpy out of the object to the public virtual function, public member functions can be normal access, because the C + + class member function address is shared, through the this pointer to check whether the unique
C + + Singleton pattern Code Analysis