In a powerful computer programming language such as C ++, there are many complicated functions that require us to accumulate experience in practice and clarify the application characteristics of these functions. Here we will first look at the implementation methods of the C ++ single-piece mode.
Example code of C ++ single-piece mode:
- class Singleton
- {
- public:
- static Singleton * Instance()
- {
- if( 0== _instance)
- {
- _instance = new Singleton;
- }
- return _instance;
- }
- protected:
- Singleton(){}
- virtual ~Singleton(void){}
- static Singleton* _instance;
- };
2) use smart pointers for garbage collection
- class Singleton
- {
- public:
- ~Singleton(){}
- static Singleton* Instance()
- {
- if(!pInstance.get())
- {
- pInstance = std::auto_ptr<Singleton>(new Singleton());
- }
- return pInstance.get();
- }
- protected:
- Singleton(){}
- private:
- static std::auto_ptr<Singleton> pInstance;
- };
The preceding steps are related to the C ++ single-piece mode.