http://blog.csdn.net/hackbuteer1/article/details/7460019
For thread safety and exception security, the following extensions can be made
- Class Lock
- {
- Private
- CCriticalSection M_cs;
- Public
- Lock (CCriticalSection CS): M_cs (CS)
- {
- M_cs. Lock ();
- }
- ~lock ()
- {
- M_cs. Unlock ();
- }
- };
- Class Singleton
- {
- Private
- Singleton ();
- Singleton (const Singleton &);
- singleton& operator = (const Singleton &);
- Public
- static Singleton *instantialize ();
- static Singleton *pinstance;
- Static CCriticalSection CS;
- };
- singleton* Singleton::p instance = 0;
- singleton* singleton::instantialize ()
- {
- if (pinstance = = NULL)
- { //double check
- Lock Lock (CS); //Use lock for thread safety and resource management classes for exception security
- //Using the Resource management class, when an exception is thrown, the resource management class object is destroyed, and the destructor always occurs whether the exception is thrown or the statement block ends.
- if (pinstance = = NULL)
- {
- Pinstance = new Singleton ();
- }
- } ---//my Note: The Lock class here is a local variable, which is then refactored, which will be unlocked.
- return pinstance;
- }
"Go" C + + Singleton mode