0

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

6
Contributors
5
Replies
6
Views
7 Years
Discussion Span
Last Post by mike_2000_17
Featured Replies
  • 1
    Narue 5,707   7 Years Ago

    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." Read More

1

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."

0

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 ;)

-4
#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;

}

Edited by Ezzaral: Added code tags. Please use them to format any code that you post.

0

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)).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.