C++单件模式实现代码详解

在C++这样一款功能强大的计算机编程语言中,有很多比较复杂的功能,需要我们在不断的实践中去积累经验,理清这些功能的应用特点。在这里我们就先来了解一下C++单件模式的相关实现方式。

C++单件模式代码示例:

 
 
 
  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) 利用智能指针进行垃圾回收

 
 
 
  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. }; 

以上就是对C++单件模式的相关操作步骤。

【编辑推荐】

  1. C++获取文件具体方法详解
  2. C++ makefile写法标准格式简介
  3. C++统计对象个数方法详解
  4. C++ #define预处理指令特点评比
  5. C++二维数组初始化相关应用技巧分享
THE END