继承类实现单例模式
废话不多,直接上父类代码
#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;
本文介绍了一种基于模板的单例模式实现方法,并通过一个具体示例展示了如何使用该单例模式。此方法利用了C++11标准库中的`std::call_once`和`std::once_flag`来确保线程安全地初始化单例对象。
2450





