I have a question about the singleton pattern.
I saw two cases concerning the static member in the singleton class.
First it is an object, like this
A better approach is to create a singleton class. This also avoids the instance availability check in the GetInstance() function. This can be achieved using a function pointer.
class TSingleton;
typedef TSingleton* (*FuncPtr) (void);
class TSingleton {
TSingleton(); //prevent public object creation
TSingleton (const TSingleton& pObject); // prevent copying object
static TSingleton* vObject; // single object of a class
static TSingleton* CreateInstance (void);
static TSingleton* Instance (void);
public:
static FuncPtr GetInstance;
};
FuncPtr TSingleton::GetInstance = CreateInstance;
TSingleton* TSingleton::vObject;
TSingleton::TSingleton()
{
}
TSingleton::TSingleton(const TSingleton& pObject)
{
}
TSingleton* TSingleton::CreateInstance(void)
{
if(vObject == NULL){
// Introduce here some code for taking lock for thread safe creation
//...
//...
//...
if(vObject == NULL){
vObject = new TSingleton();
GetInstance = Instance;
}
}
return vObject;
}
TSingleton* TSingleton::Instance(void)
{
return vObject;
}
void main()
{
TSingleton::GetInstance(); // this will call TSingleton::Createinstance()
TSingleton::GetInstance(); // this will call TSingleton::Instance()
// all further calls to TSingleton::GetInstance will call TSingleton::Instance() which simply returns already created object.
}
I agree with Billy. In 2nd approach we are dynamically allocating memory from the heap using new. This memory remains always and never gets freed, unless a call to delete is been made. Hence the Global pointer approach creates a memory leak.
class singleton
{
private:
static singleton* single;
singleton()
{ }
singleton(const singleton& obj)
{ }
public:
static singleton* getInstance();
~singleton()
{
if(single != NULL)
{
single = NULL;
}
}
};
singleton* singleton :: single=NULL;
singleton* singleton :: getInstance()
{
if(single == NULL)
{
single = new singleton;
}
return single;
}
int main() {
singleton *ptrobj = singleton::getInstance();
delete ptrobj;
singleton::getInstance();
delete singleton::getInstance();
return 0;
}