继承类实现单例模式
废话不多,直接上父类代码
#ifndef __SINGLETON_H__
#define __SINGLETON_H__
#include <iostream>
#include <memory>
#include <mutex>
template<typename T>
class Singleton {
public:
static T* GetInstance()
{
static std::once_flag s_flag;
std::call_once(s_flag, [&]() {
m_pSington.reset(new T());
});
return m_pSington.get();
}
void PrintAddress() const
{
std::cout << this << std::endl;
}
protected:
Singleton(){};
~Singleton(){};
static std::shared_ptr<T> m_pSington;
private:
Singleton(const Singleton&) = delete;
Singleton& operator=(const Singleton&) = delete;
private:
};
template<typename T> std::shared_ptr<T> Singleton<T>::m_pSington;
#endif //__SINGLETON_H__
单例使用方法
class CBaseConfig : public Singleton<CBaseConfig>
{
public:
CBaseConfig();
~CBaseConfig();
std::string GetComId() const { return m_comId; }
void SetComId(std::string val) { m_comId = val; }
private:
// 基础参数
std::string m_comId;
std::string m_nodeId;
}
调用代码如下
CBaseConfig *tmp = CBaseConfig::GetInstance();
std::cout << "conid:" << tmp->GetComId() << ",nodeid:" << tmp->GetNodeId() << std::endl;