#include <iostream>
using std::cout;
using std::endl;
class Singleton{
public:
static Singleton& getInstance();//返回引用类型,避免产生对象副本,提高效率
~Singleton();
private:
Singleton();
static Singleton* state;
static int count;//测试标志,可有可无
};
Singleton* Singleton::state = 0;
int Singleton::count = 0;
Singleton::Singleton()
{
count++;
cout<<"构找了第"<<count<<"个实例"<<endl;
}
Singleton& Singleton::getInstance()
{
if(!state)
state = new Singleton();
return *state;
}
Singleton::~Singleton()
{
if(state) //刚加上去的判断
delete state;
state = 0;
}
int main(void)
{
Singleton test1 = Singleton::getInstance();
Singleton test2 = Singleton::getInstance();//不进行对象构造
return 0;
}
本文介绍了一种使用C++实现单例模式的方法。通过静态成员函数getInstance()确保类仅有一个实例,并提供全局访问点。文章展示了如何避免对象副本的创建以提高效率,并通过计数变量来跟踪实例数量。
1517

被折叠的 条评论
为什么被折叠?



