饿汉式,static对象,代码加载时即生成了 分配了空间。这点也是和懒汉式主要的区别,懒汉式是new出来的,程序调用的时候才分配空间。
空间和效率的差异!
///
/*单例模式:饿汉式 实现1 */
#include <iostream>
using namespace std;class singleInst
{
public:
void printLog()
{
printf("call printLog()\n");
}
private:
/*构造函数被私有化(如果用户定义的类中没有显式的定义任何构造函数,
编译器就会自动为该类型生成默认构造函数)*/
singleInst(int No)
{
printf("call singleInst()\n");
}
/*使用局部静态变量,来解决析构问题,且又不影响单实例的唯一性*/
~singleInst()
{
printf("call ~singleInst()\n");
}
/*禁止拷贝*/
/*拷贝构造函数声明为私有,并不提供实现*/
singleInst(const singleInst &);
/*复制运算符声明为私有,并不提供实现*/
singleInst & operator = (const singleInst &);
public:
static singleInst & GetInst() { static singleInst m_inst(1); return m_inst; }
};
int main()
{
singleInst &testInst = singleInst::GetInst();
testInst .printLog();
return 0;
}
///
/*单例模式:饿汉式 实现2 */
using namespace std;
class singleInst
{
public:
void printLog()
{
printf("call printLog()\n");
}
private:
singleInst(int No)
{
printf("call singleInst()\n");
}
~singleInst()
{
printf("call ~singleInst()\n");
}
singleInst(const singleInst &);
/*singleInst & operator = (const singleInst &); 下面返回指针,此函数可以不声明*/
public:
static singleInst * GetInst() { static singleInst m_inst(1); return &m_inst; }
};
int main()
{
singleInst *testInst = singleInst::GetInst();
testInst ->printLog();
return 0;
}