首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

关于C++单例模式的1点小疑问。

2013-11-29 
关于C++单例模式的一点小疑问。。。#include stdafx.h#include iostreamusing namespace stdclass A{pub

关于C++单例模式的一点小疑问。。。


#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
public:
static A* instance()
{
static A _a;
return &_a;
}
void setNum(int num)
{
this->num = num;
}
void getNum()
{
cout<<"num:"<<this->num<<endl;
//return this.num;
}
private:
A();
private:
int num;
};
A::A(){};

class B
{
public:
static B* instance()
{
return b;
}
void setNum(int num)
{
this->num = num;
}
void getNum()
{
cout<<"num:"<<this->num<<endl;
//return this.num;
}
private:
B();
static B *b;
int num;
};
B::B(){};
B* B::b = new B();

class C
{
public:
static C* instance()
{
if (c==NULL)
{
c = new C();
}
return c;
}
void setNum(int num)
{
this->num = num;
}
void getNum()
{
cout<<"num:"<<this->num<<endl;
//return this.num;
}
private:
C();
static C *c;
int num;
};
C::C(){};
C* C::c = NULL;

int main( )
{
A::instance()->setNum(15);
A::instance()->getNum();
B::instance()->setNum(16);
B::instance()->getNum();
C::instance()->setNum(17);
C::instance()->getNum();
system("pause");
return 0;
}


这边我用C++实现了这三种单例模式,B和C是参照饿汉式懒汉式写的,感觉A也好像实现了单例模式,而且更简单的样子,但是觉得应该会存在什么问题,只是发现不到。。。有人可以指导下吗。。。

不用考虑多线程,单线程的情况下。
[解决办法]
A和C都是延迟实例化. A没有的堆上创建对象,所以不能提前销毁,当然开销也较C小。 C刚好相反。  

热点排行