C++ 单例模式的实现及资源释放

局部静态变量

优点: 不需要考虑资源释放,程序结束时,静态区资源自动释放

#ifndef SINGLETON_H
#define SINGLETON_H

class Singleton 
{
public:
    static Singleton& getInstance()
    {
        static Singleton instance;
        return instance;
    }
private:
    Singleton() {};
    Singleton(const Singleton&);
    Singleton& operator=(const Singleton&);
};
#endif //SINGLETON_H
#ifndef SINGLETON_H
#define SINGLETON_H

class Singleton 
{
public:
    static Singleton* getInstance()
    {
        static Singleton instance;
        return &instance;
    }
private:
    Singleton() {};
};
#endif //SINGLETON_H

懒汉式

第一次调用时才初始化,避免内存浪费,但是为保证多线程下安全,必须加锁

#ifndef SINGLETON_H
#define SINGLETON_H
#inlcude 

class Singleton 
{
public:
    static Singleton* getInstance();
private:
    Singleton() {};
private:
    static Singleton *m_pSingleton;
    static mutex m_mutex;
};
#endif //SINGLETON_H
//singleton.cpp
#include "singleton.h"

using namespace std;
Singleton *Singleton::m_pSingleton = NULL;
mutex Singleton::m_mutex;

Singleton  *Singleton::getInstance()
{
    if (m_pSingleton == NULL)
    {
        Lock_guard<mutex> lock(m_mutex);
        if (m_pSingleton == NULL)
        {
            m_pSingleton = new Singleton();
        }
    }
    return m_pSingleton;
}

饿汉式

类加载时就初始化,会浪费内存,但线程安全

#ifndef SINGLETON_H
#define SINGLETON_H
#inlcude 

class Singleton 
{
public:
    static Singleton* getInstance();
private:
    Singleton() {};
private:
    static Singleton *m_pSingleton;
};
#endif //SINGLETON_H
//singleton.cpp
#include "singleton.h"

using namespace std;
Singleton *Singleton::m_pSingleton = new Singleton();

Singleton  *Singleton::getInstance()
{
    return m_pSingleton;
}

资源释放

谁分配,谁释放。。。这里懒汉与饿汉式都需要进行资源释放。可利用静态局部变量由程序自动释放特点来进行

#ifndef SINGLETON_H
#define SINGLETON_H
#inlcude 

class Singleton 
{
public:
    static Singleton* getInstance();
private:
    Singleton() {};
private:
    static Singleton *m_pSingleton;

    class GC 
    {
    public:
        ~GC()
        {
            if (m_pSingleton!=NULL)
            {
                delete m_pSingleton;
                m_pSingleton = NULL;
            }
        }
        static GC gc;
    };
};
#endif //SINGLETON_H
//singleton.cpp
Singleton::GC Singleton::GC::gc;  //添加此行进行static 变量定义

你可能感兴趣的:(设计模式)