此单例模式非内存泄漏非线程安全。
singleton.h
#pragma once
#define DISALLOW_COPY(TypeName) \
TypeName(const TypeName&){}
#define DISALLOW_ASSIGN(TypeName) \
TypeName operator=(const TypeName&){}
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
TypeName(const TypeName&) {} \
TypeName operator=(const TypeName&){}
#include <memory>
#include <iostream>
using namespace std;
class Singleton
{
public:
~Singleton();
private:
explicit Singleton();
DISALLOW_COPY_AND_ASSIGN(Singleton)
public:
static Singleton *getInstance();
private:
static Singleton *m_pInstance;
// static std::shared_ptr<Singleton> m_pInstance;
//private:
// class Deleter
// {
// public:
// Deleter()
// {
// cout << "Deleter()" << endl;
// }
// ~Deleter()
// {
// cout << "~Deleter()" << endl;
// if (NULL != Singleton::m_pInstance)
// {
// delete Singleton::m_pInstance;
// }
// }
// };
// // 定义一个静态的Deleter实例
// static Deleter deleter;
};
singleton.cpp
#include "Singleton.h"
Singleton *Singleton::m_pInstance;
//std::shared_ptr<Singleton> Singleton::m_pInstance;
//Singleton::Deleter Singleton::deleter;
Singleton::~Singleton()
{
cout << "~Singleton()" << endl;
}
Singleton::Singleton()
{
cout << "Singleton()" << endl;
}
Singleton *Singleton::getInstance()
{
// //懒汉模式(会内存泄漏, 如果类内部定义静态Deleter实例也不会内存泄露)
// if (NULL == m_pInstance)
// m_pInstance = new Singleton();
// return m_pInstance;
//饿汉模式(不会内存泄露)
static Singleton instance;
return &instance;
// //懒汉模式(采用智能指针,不会内存泄漏)
// if (nullptr == m_pInstance.get())
// {
// m_pInstance = std::auto_ptr<Singleton>(new Singleton);
// }
// return m_pInstance.get();
}
切记一点:Qt项目中,单例模式主动delete窗体会和Qt本身对象树析构机制冲突,造成二次析构,从而导致出现无法访问0xfffffffe之类的错误,Qt析构机制只是将对象delete掉,并不会将对象置为NULL。