Detailed description of the implementation code of the C ++ single-piece Mode

Source: Internet
Author: User

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:

 
 
  1. class Singleton  
  2. {  
  3. public:  
  4. static Singleton * Instance()  
  5. {  
  6. if( 0== _instance)  
  7. {  
  8. _instance = new Singleton;  
  9. }  
  10. return _instance;  
  11. }  
  12. protected:  
  13. Singleton(){}  
  14. virtual ~Singleton(void){}  
  15. static Singleton* _instance;  
  16. }; 

2) use smart pointers for garbage collection

 
 
  1. class Singleton  
  2. {  
  3. public:  
  4. ~Singleton(){}  
  5. static Singleton* Instance()  
  6. {  
  7. if(!pInstance.get())  
  8. {  
  9. pInstance = std::auto_ptr<Singleton>(new Singleton());  
  10. }  
  11. return pInstance.get();  
  12. }  
  13. protected:   
  14. Singleton(){}  
  15. private:  
  16. static std::auto_ptr<Singleton> pInstance;  
  17. }; 

The preceding steps are related to the C ++ single-piece mode.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.