zoukankan      html  css  js  c++  java
  • 【设计模式】单例模式,嵌套类实现释放对象内存

    一.概述

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

  • 相关阅读:
    oop klass

    广义表
    Huffman树
    二叉搜索树
    二叉树的前序、中序、后序、层序遍历
    循环链表解决约瑟夫环问题
    搭建局域网SVN代码服务器
    【CheckList】精简用例,提升执行效率,减少漏测(总结篇)
    测试资源不同时,如何有针对性的设计测试用例?
  • 原文地址:https://www.cnblogs.com/woniu201/p/11694564.html
Copyright © 2011-2022 走看看