Hai everyone
Can u please help me in writing a basic singleton programme in C++ and please explain code that are specially used to make the class singleton

else please send a link where I can get the same
Thanq
Have a nice day

Recommended Answers

All 5 Replies

And what have you done to help yourself first? Your question sounds a lot like "I don't want to think, do it for me."

And what have you done to help yourself first? Your question sounds a lot like "I don't want to think, do it for me."

just don't beat him up too hard ;)

#try this

#include <windows.h>
#include <process.h>
#include <assert.h>

class MyCriticalSection : public CRITICAL_SECTION
{
public:
    MyCriticalSection(){
        InitializeCriticalSection(this);
    }
    virtual ~MyCriticalSection()
    {
        DeleteCriticalSection(this);
    }
};

class CThreadSafeSingleton
{
public:
    static CThreadSafeSingleton * getInstance();  
protected:
    CThreadSafeSingleton() {} ;

private:

    static CThreadSafeSingleton * instance;
    static MyCriticalSection myCriticalSection; 
};

CThreadSafeSingleton * CThreadSafeSingleton::instance = 0;
MyCriticalSection CThreadSafeSingleton::myCriticalSection;

CThreadSafeSingleton * CThreadSafeSingleton::getInstance()
{

 	EnterCriticalSection(&myCriticalSection);
	if ( instance == NULL )
	{
		instance = new (nothrow) CThreadSafeSingleton();
        assert(instance);
	}
	LeaveCriticalSection(&myCriticalSection);
	return instance;

}

This is the basic singleton implementation. (I'm giving the link because, if you are going to look on the internet to find a copy-pastable implementation of it, you might find a poor one (like the one from AndySpb) and screw your code up with it, so at least, this link has a proper implementation (but only a very basic one, i.e. no thread-safety and no cross-modularity or ABI)).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.