C++单例模式
Posted Overboom
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C++单例模式相关的知识,希望对你有一定的参考价值。
1. 什么是单例模式
因为在设计或开发中,肯定会有这么一种情况,一个类只能有一个对象被创建,如果有多个对象的话,可能会导致状态的混乱和不一致。这种情况下,单例模式是最恰当的解决办法。
2. 单例模式实现
Singleton.cpp
#include "Singleton.h"
#include <iostream>
std::weak_ptr<CSingleton> CSingleton::m_instance;
int CSingleton::num = 10;
CSingleton::CSingleton()
{
}
CSingleton::~CSingleton()
{
}
int CSingleton::showNum()
{
return num;
}
std::shared_ptr<CSingleton> CSingleton::get_instance()
{
std::shared_ptr<CSingleton> instance = m_instance.lock();
if(!instance)
{
printf("%s: create an CSingleton object!\\n", __FUNCTION__);
instance.reset(new CSingleton());
m_instance = instance;
num+=1;
}
else
{
printf("%s exist CSingleton object\\n
以上是关于C++单例模式的主要内容,如果未能解决你的问题,请参考以下文章