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

版权声明:本文为CSDN博主woniu211111原创文章,未经博主允许不得转载。联系方式:[email protected] https://blog.csdn.net/woniu211111/article/details/84835905

一.概述

     单例模式就是一个类只能被实例化一次 ,也就是只能有一个实例化的对象的类。减少每次都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;
}

猜你喜欢

转载自blog.csdn.net/woniu211111/article/details/84835905