巧用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!\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.cpp

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

  输出:

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

上一篇:(转载)linux中shell变量


下一篇:DB2中SQLSTATE=57016 SQLCODE=-668