巧用std::shared_ptr全局對象釋放單例內存

巧用std::shared_ptr

單例的使用相對比較普遍,可是須要在程序退出前調用它的析構函數對數據進行釋放,常規作法是在main函數末尾進行釋放工做,ios

可是這樣相對比較繁瑣,所以便有了利用全局變量由系統負載析構的特色,定義一個全局str::shared_ptr對象,對象指定對單例進行析構。函數

所以不須要咱們關心什麼時候析構單例,堪稱方便。對象

  SingleObject.hppblog

#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.cppio

#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!\n";
}

SingleObject::~SingleObject()
{
	std::cout << "This is the destructor of SingleObject class!\n";
}

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!\n";
	}
}

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!\n";
}

  main.cppclass

#include <iostream>
#include "SingleObject.hpp"

int main(int argc, char **argv)
{
	SingleObject::GetInstance().DoSomeThing();
	
	return 0;
}

  輸出:stream

 

相關文章
相關標籤/搜索