Friday, April 2, 2010

Singleton Class using shared_ptr

Hi All,

Today I have come across one class called shared_ptr which has one good constructor which can accept function pointer. This function will be called by destructor of shared_ptr. Hence this function can be used for releasing SINGLETON CLASS REFERENCE.

Lets see the code:-

Singleton.h

#ifndef __SINGLETON__
#define __SINGLETON__

namespace myapp
{
class SingletonPattern
{
public:
static SingletonPattern* GetInstance();
void Release();
private:
SingletonPattern();
SingletonPattern(const SingletonPattern&);
~SingletonPattern();
SingletonPattern& operator =(const SingletonPattern&);
private:
static SingletonPattern* m_pSinglePattern;
static int m_Count;
};

void Release(SingletonPattern* obj);
};

#endif //__SINGLETON__

Singleton.cpp


#include "stdafx.h"

#include "Singleton.h"

using namespace myapp;

SingletonPattern* SingletonPattern::m_pSinglePattern = NULL;
int SingletonPattern::m_Count=0;

SingletonPattern::SingletonPattern()
{
}

SingletonPattern::SingletonPattern(const SingletonPattern &)
{
}

SingletonPattern::~SingletonPattern()
{
}

SingletonPattern& SingletonPattern::operator =(const SingletonPattern& rhs)
{
if (this != &rhs) {
// Deallocate, allocate new space, copy values...
}
return *this;
}

SingletonPattern* SingletonPattern::GetInstance()
{
if(NULL == m_pSinglePattern)
{
m_pSinglePattern = new SingletonPattern;
}

m_Count++;

return m_pSinglePattern;
}

void SingletonPattern::Release()
{
if(m_Count > 0) --m_Count;
if(NULL != m_pSinglePattern && 0 == m_Count)
{
delete m_pSinglePattern;
m_pSinglePattern = NULL;
}
}

void myapp::Release(SingletonPattern* obj)
{
if(NULL != obj) obj->Release();
}

SingletonTest.cpp

Main Function

#include "stdafx.h"

#include "vld.h"

#include "Singleton.h"

using namespace myapp;

using namespace std::tr1;

int _tmain(int argc, _TCHAR* argv[])
{
shared_ptr objshared(SingletonPattern::GetInstance(), Release);

shared_ptr objshared1(SingletonPattern::GetInstance(), Release);

return 0;
}

Singleton class reference will be release automatically when destructor of shared_ptr class is called.

Hence when main function is about to finish, shared_ptr destructor will be called and finally release function will be called.

We neednot have call Release explicitly for singleton class.

We cannot use auto_ptr because there is no such constructor which accepts function pointer.

No comments:

Post a Comment