-
July 5th, 2010, 06:33 AM
#1
C++ Singleton Problem
I have the code for a singleton below, and I am getting a linker error "multiple definitions " when i include the singleton.h file in more than one C++ file. This singleton code should cope with up to 5 singletons in a process and report error above that.
The singleton clas is all in the .h file:
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 // !defined(AFX_MYSINGLETON_H__8AA85488_875D_11DF_985E_0090F508B061__INCLUDED_)
CMySingleton::~CMySingleton()
{
--nCount; // Decrement number of instances
}
CMySingleton* CMySingleton::CreateInstance()
{
CMySingleton* ptr = NULL;
if(nMaxInstance > nCount)
{
ptr = new CMySingleton;
++nCount; // Increment no of instances
}
return ptr;
}
int CMySingleton::nCount = 0;
int CMySingleton::nMaxInstance = 5; // When maxInstance is 1, we have a pure singleton class
// end CMySingleton.h
The multiple definition link errors occur on :
CMySingleton::nCount
int CMySingleton::nMaxInstance
for eg.
NOTE: This code works if i include it once , in main.cpp, in that case it compiles and links and runs.
But i do need to include it in more than one *.cpp file:
Any Advice appreciated.
Thanks
Marco
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|