zoukankan      html  css  js  c++  java
  • C++单例模式的经典实现(Singleton)

    C++单例经典实现

    本文主要介绍C++使用中的单例的两种经典实现,基本可满足一般的使用,主要分为饿汉模式懒汉模式两种

    饿汉模式

    class Singleton
    {
    public:
    	static Singleton* getInstance();
    
    private:
    	Singleton(){}
    	//把复制构造函数和=操作符也设为私有,防止被复制
    	Singleton(const Singleton&){}
    	Singleton& operator=(const Singleton&){}
    
    	static Singleton* instance;
    public:
    	owndata   data;   //单例中需要使用的自定义数据
    };
    //手动进行初始
    Singleton* Singleton::instance = new Singleton();
    Singleton* Singleton::getInstance()
    {
    	return instance;
    }
    

    饿汉模式通过直接在静态区初始化instance,保证了在调用前就做好开销,不存在多线程调用时的初始化问题。

    懒汉模式

    class Singleton;
    
    Singleton::AutoGC Singleton::gc;
    Singleton* Singleton::pSingleton = NULL;
    
    class Singleton
    {
    private:
    	static Singleton* pSingleton;
    private:
        Singleton(){}
    	//把复制构造函数和=操作符也设为私有,防止被复制
    	Singleton(const Singleton&);
    	Singleton& operator=(const Singleton&);
    public:
    	static Singleton* getSingleton()
    	{
    	    //双重锁定,提高多线程操作时的效率
    		if (pSingleton == NULL)
    		{
    			Lock(); //根据环境的需要进行不同锁的实现,推荐boost库
    			if (pSingleton == NULL)
    				pSingleton = new Singleton();
    			Unlock();
    		}
    		return pSingleton;
    	}
    
    	class AutoGC // 垃圾回收类
    	{
    	public:
    		AutoGC(){}
    		~AutoGC()
    		{
    			if (pSingleton != NULL)
    			{
    				delete pSingleton;
    				pSingleton = NULL;
    			}
    		}
    	};
    	static AutoGC gc;
    
    public:
    	owndata   data;   //单例中需要使用的自定义数据
    };
    

    懒汉模式主要意义在于调用时生成,防止过早的系统开销,这种方式更加复杂,牵涉到多线程的同步问题。
    在这个懒汉模式中加入了自动的注销回收,避免在程序结束时出现泄露。

  • 相关阅读:
    75. Sort Colors
    101. Symmetric Tree
    121. Best Time to Buy and Sell Stock
    136. Single Number
    104. Maximum Depth of Binary Tree
    70. Climbing Stairs
    64. Minimum Path Sum
    62. Unique Paths
    css知识点3
    css知识点2
  • 原文地址:https://www.cnblogs.com/chencarl/p/7680699.html
Copyright © 2011-2022 走看看