Re: C++ Singleton Problem
Move the definition part into a cpp file and leave just the declaration part in the header.
Re: C++ Singleton Problem
Hello Sir/madam~, I am find there are many links over google about the singleton, can you give me typical example of singletoon in windows XP coding Micosoft window?
Thank you
Re: C++ Singleton Problem
Quote:
Originally Posted by
S_M_A
Move the definition part into a cpp file and leave just the declaration part in the header.
That is what I had in the first place, and it just would not compile or link then.
I only got it working by moving everything into one header file. And it worked for one include into main.cpp;
But when i created another test.cpp file to check whether it would limit the number of singletons as designed, it gave the link errors I originally posted.
Re: C++ Singleton Problem
Try this: main.cpp
Code:
#include "singleton.h"
// Didn't bother to create a header
void CreateSingleton();
void DeleteSingleton();
int main(int argc, char* argv[])
{
CMySingleton* ptr = CMySingleton::CreateInstance();
CreateSingleton();
delete ptr;
DeleteSingleton();
return 0;
}
singleton.h
Code:
#ifndef _SINGLETON_H
#define _SINGLETON_H
class CMySingleton
{
private:
CMySingleton(){}; // Private Constructor
static int nCount; // Current number of instances
static int nMaxInstance; // Maximum number of instances
public:
~CMySingleton(); // Public Destructor
static CMySingleton* CreateInstance(); // Construct Indirectly
//Add whatever members you want
};
#endif
singleton.cpp
Code:
#include "singleton.h"
CMySingleton* CMySingleton::CreateInstance()
{
CMySingleton* ptr = NULL;
if(nMaxInstance > nCount)
{
ptr = new CMySingleton;
++nCount; // Increment no of instances
}
return ptr;
}
CMySingleton::~CMySingleton()
{
--nCount; // Decrement number of instances
}
int CMySingleton::nCount = 0;
int CMySingleton::nMaxInstance = 5; // When maxInstance is 1, we have a pure singleton class
otherfile.cpp
Code:
#include "singleton.h"
static CMySingleton* ptr;
void CreateSingleton()
{
ptr = CMySingleton::CreateInstance();
}
void DeleteSingleton()
{
delete ptr;
}