【设计模式】单例模式,嵌套类实现释放对象内存

一.概述

     单例模式就是一个类只能被实例化一次 ,也就是只能有一个实例化的对象的类。减少每次都new对象的开销,节省系统资源,同时也保证了访问对象的唯一实例。常用于
如下场景:
1.频繁实例化然后销毁的对象。
2.创建对象太耗时,消耗太多资源,但又经常用到。

二.代码实现

C++11代码实现,

/********************************************************
Copyright (C),  2016-2018,
FileName:		main
Author:        	woniu201
Created:       	2018/12/05
Description:	C++ 单例模式
********************************************************/
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;


class CSingleton
{
public:

	static CSingleton* GetInstance()
	{
		if (singleton == NULL) //两个NULL可以提高获取实例效率
		{
			std:lock_guard<mutex> lock(m_mutext); //封装lock,unlock,出作用域会自动解锁
			if (singleton == NULL)
			{
				singleton = new CSingleton();
				static CGC c1;
			}
		}
		return singleton;
	}

	class CGC  //类中嵌套类,用于释放对象
	{
	public:
		~CGC()
		{
			if (CSingleton::singleton)
			{
				delete CSingleton::singleton;
				CSingleton::singleton = NULL;
				cout << "释放对象" << endl;
			}
		}
	};

	//成员函数
	void fun1()
	{
		cout << "this is test!" << endl;
	}
private:
	CSingleton() {}
	static CSingleton* singleton;
	static std::mutex m_mutext;
};

//类外初始化静态成员
CSingleton* CSingleton::singleton = NULL;
mutex CSingleton::m_mutext;

/************************************
@ Brief:		线程函数
@ Author:		woniu201 
@ Created:		2018/12/05
@ Return:            
************************************/
void threadFun()
{
	CSingleton* obj = CSingleton::GetInstance();
	obj->fun1();
	cout << "实例地址:" << obj << endl;
}

int main()
{
	thread t1(threadFun);
	thread t2(threadFun);
	t1.join();
	t2.join();
	return 1;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农code之路

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值