设计模式之单例模式
来源:互联网 发布:如何判断存在sql注入 编辑:程序博客网 时间:2024/04/19 18:05
此单例模式非内存泄漏非线程安全。
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。
阅读全文
0 0
- 设计模式之 单例设计模式
- 设计模式之 单例设计模式
- 设计模式之单例设计模式
- 设计模式之-----------单例设计模式
- 设计模式之:单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之单例设计模式
- 设计模式之-单例设计模式
- 设计模式之单例设计模式 标签: 设计模式
- 设计模式之单例
- 设计模式之单例
- 设计模式之 单例
- MyBatis逆向工程自动生成代码
- 散列表查找实现
- 教你防范勒索软件:加强网络环境的6条建议
- 各种选项卡
- 设计模式-单例模式
- 设计模式之单例模式
- Jmeter后置处理器-正则表达式提取器
- adaBoost 源码
- MySQL引擎详解
- MPAndroidChart开源图表库之饼状图
- 前端安全之XSS攻击
- 动态sql
- xml解析
- 使用Windriver生成CPCI驱动