• 巧用std::shared_ptr全局对象释放单例内存


    巧用std::shared_ptr

    单例的使用相对比较广泛,但是需要在程序退出前调用它的析构函数对数据进行释放,常规做法是在main函数末尾进行释放工作,

    但是这样相对比较繁琐,因此便有了利用全局变量由系统负载析构的特点,定义一个全局str::shared_ptr对象,对象指定对单例进行析构。

    因此不需要我们关心何时析构单例,堪称方便。

      SingleObject.hpp

    #ifndef SINGLEOBJECT_H
    #define SINGLEOBJECT_H
    
    class SingleObject
    {
    public:
    	static SingleObject& GetInstance();
    	static SingleObject* GetInstancePtr();
    	static void DoSomeThing();
    	static void DelObj();
    private:
    	static void NewObj();
    	SingleObject();
    	~SingleObject();
    	
    	static SingleObject* msObj;
    };
    
    #endif // SINGLEOBJECT_H
    

      SingleObject.cpp

    #include "SingleObject.hpp"
    #include <iostream>
    #include <memory>
    
    std::shared_ptr<SingleObject> SingleObjectDeletor( SingleObject::GetInstancePtr(), [](SingleObject *){ SingleObject::GetInstance().DelObj(); });
    
    SingleObject* SingleObject::msObj = NULL;
    
    SingleObject::SingleObject()
    {
    	std::cout << "This is the constructor of SignleObject class!
    ";
    }
    
    SingleObject::~SingleObject()
    {
    	std::cout << "This is the destructor of SingleObject class!
    ";
    }
    
    void SingleObject::NewObj()
    {
    	if( NULL == msObj )
    	{
    		// lock
    		msObj = new SingleObject();
    		
    		// unlock
    	}
    	
    	std::cout << "New an object, address: " << +msObj << std::endl;
    }
    
    void SingleObject::DelObj()
    {
    	if( NULL != msObj )
    	{
    		delete msObj;
    		std::cout << "Delete an object!
    ";
    	}
    }
    
    SingleObject* SingleObject::GetInstancePtr()
    {
    	if( NULL == msObj )
    	{
    		NewObj();
    	}
    	
    	return msObj;
    }
    
    SingleObject& SingleObject::GetInstance()
    {
    	if( NULL == msObj )
    	{
    		NewObj();
    	}
    	
    	return *msObj;
    }
    
    void SingleObject::DoSomeThing()
    {
    	std::cout << "SingleObject do some thing!
    ";
    }
    

      main.cpp

    #include <iostream>
    #include "SingleObject.hpp"
    
    int main(int argc, char **argv)
    {
    	SingleObject::GetInstance().DoSomeThing();
    	
    	return 0;
    }
    

      输出:

     

  • 相关阅读:
    leetcode——91.解码方法
    leetcode——64.最小路径和
    Layui上传图片2.0版
    LINQ中判断日期时间段
    Http基础
    Js中数组,字符串的常用方法
    C#数组,ArrayList,List区别
    08-01 通过线性回归了解算法流程
    08-00 课程习得
    C-02 推荐系统
  • 原文地址:https://www.cnblogs.com/zhanghang-BadCoder/p/9543777.html
Copyright © 2020-2023  润新知