C++友缘类friend在自动释放模板单例中的使用

以下为实现代码:


#pragma region 自动释放模板单例
template<typename T>
class CSingletonFree;
template<typename T>
class CSingleton
{
public:
	static T*GetInstance()
	{
		if (m_pInstance == nullptr)
		{
			unique_lock<mutex> lg(m_mtx);
			if (m_pInstance == nullptr)
			{
				m_pInstance = new T;
				//cout << "创建单列" << endl;
				m_AutoFree.Instance = &m_pInstance;
			}
		}
		return m_pInstance;
	}

protected:
	CSingleton()
	{

	}
	virtual~CSingleton()
	{
		//cout << "释放单列" << endl;
	}
private:
	static T*m_pInstance;
	static mutex m_mtx;
	static CSingletonFree<T> m_AutoFree;
	CSingleton(const CSingleton&) {};
	CSingleton& operator=(const CSingleton&) {};
};

template<typename T>
T*CSingleton<T>::m_pInstance = nullptr;
template<typename T>
mutex CSingleton<T>::m_mtx;
template<typename T>
CSingletonFree<T> CSingleton<T>::m_AutoFree;
//自动释放
template<typename T>
class CSingletonFree
{
public:
	T * * Instance = nullptr;
	~CSingletonFree()
	{
		//cout << "自动释放" << endl;
		if (Instance)
		{
			if (*Instance)
			{
				delete *Instance;
				*Instance = nullptr;
			}
			Instance = nullptr;
		}
		//cout << "释放结束" << endl;
	}
};
#pragma endregion

以下为使用案例:


//单列使用例子
class ExampleSingleton :public CSingleton<ExampleSingleton>
{
public:
	int *Num;
	~ExampleSingleton()
	{
		//cout << "释放ExampleSingleton" << endl;
		//释放代码
		if (Num)
		{
			delete Num;
			Num = nullptr;
		}
	};
private:
	ExampleSingleton() {};//防止外部创建
	friend class CSingleton<ExampleSingleton>;

};

调用时请注意:


int main()
{

	ExampleSingleton* instance = ExampleSingleton::GetInstance();
	instance->Num = new int(2333);
	cout << *(instance->Num) << endl;

	//delete instance;//有自动释放这样写会报错的哦

	CON_PAUSE
	return 0;
}

转载请说明出处!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值