单列模式(懒汉)测试代码
生活随笔
收集整理的这篇文章主要介绍了
单列模式(懒汉)测试代码
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
#include <iostream>
class CSingleton /* 懒汉式 */
{
public:
static CSingleton *GetInstance()
{
if(m_pInstance == NULL) //判断是否第一次调用
{
m_pInstance = new CSingleton();
}
return m_pInstance;
}
void RelaseInstance()
{
delete this;
}
void HelloWorld(void)
{
std::cout<<"Hello world!"<<std::endl;
}
private:
CSingleton() //构造函数是私有的
{
}
CSingleton(const CSingleton& that)//拷贝构造函数也应是私有的
{
}
~CSingleton()
{
m_pInstance = NULL;
}
static CSingleton *m_pInstance;
};
/*
1.一定要放在类定义后面初始化,放到前面就会报错。
2.一定要对这个静态类成员变量初始化,否则编译时报引用了未定义成员的错误。
*/
CSingleton* CSingleton::m_pInstance = 0;
int main(int argc, char** argv)
{
CSingleton *m_pInstance1 = CSingleton::GetInstance();
m_pInstance1->HelloWorld();
return 0;
} 《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读
class CSingleton /* 懒汉式 */
{
public:
static CSingleton *GetInstance()
{
if(m_pInstance == NULL) //判断是否第一次调用
{
m_pInstance = new CSingleton();
}
return m_pInstance;
}
void RelaseInstance()
{
delete this;
}
void HelloWorld(void)
{
std::cout<<"Hello world!"<<std::endl;
}
private:
CSingleton() //构造函数是私有的
{
}
CSingleton(const CSingleton& that)//拷贝构造函数也应是私有的
{
}
~CSingleton()
{
m_pInstance = NULL;
}
static CSingleton *m_pInstance;
};
/*
1.一定要放在类定义后面初始化,放到前面就会报错。
2.一定要对这个静态类成员变量初始化,否则编译时报引用了未定义成员的错误。
*/
CSingleton* CSingleton::m_pInstance = 0;
int main(int argc, char** argv)
{
CSingleton *m_pInstance1 = CSingleton::GetInstance();
m_pInstance1->HelloWorld();
return 0;
} 《新程序员》:云原生和全面数字化实践50位技术专家共同创作,文字、视频、音频交互阅读
总结
以上是生活随笔为你收集整理的单列模式(懒汉)测试代码的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: preempt_count详解
- 下一篇: 快速理解桥接模式