Original Post
🔒 Locked
Singleton Class Question
Advertisement
You can't use local static's in multithreaded code (according to Modern C++.) It is also recommended that you do not return a pointer to the singleton instance as a user could technically call 'delete' on it.
The proper way to write the singleton body is:
If you know your code will only ever be single-threaded, you can write it like this:
Regards,
[edited by - Digitalfiend on May 15, 2003 9:49:05 AM]
The proper way to write the singleton body is:
static SingletonType& Instance()
{
if(!instance_)
{
Guard<Threading::Lock> guard(lock_);
if(!instance_)
{
instance_ = new SingletonType;
}
}
return *this;
}
If you know your code will only ever be single-threaded, you can write it like this:
static SingletonType& Instance()
{
if(!instance_)
{
instance_ = new SingletonType;
}
return *this;
}
Regards,
[edited by - Digitalfiend on May 15, 2003 9:49:05 AM]
Yet another Singleton implementation:
This allows nifty things like this:
So far, this Singleton model has served well for every time I've needed a Singleton. That's not saying I've run into every problem that you can have with a Singleton, I'm just saying that it's a fairly robust design for one.
[edited by - daerid on May 15, 2003 1:21:26 PM]
#if !defined( __SINGLETON_H__ )
#define __SINGLETON_H__
#ifdef _MSC_VER
# if _MSC_VER > 1200
# pragma once
# endif
#endif
template<typename _Type>
class Singleton
{
public:
Singleton();
~Singleton();
static _Type& GetInstance();
private:
static _Type* mInstance;
};
template<typename _Type>
_Type* Singleton<_Type>::mInstance = 0;
template<typename _Type>
Singleton<_Type>::Singleton()
{
assert( mInstance == 0 );
mInstance = static_cast<_Type*>( this );
}
template<typename _Type>
Singleton<_Type>::~Singleton()
{
assert( mInstance != 0 );
mInstance = 0;
}
template<typename _Type>
_Type& Singleton<_Type>::GetInstance()
{
assert( mInstance != 0 );
return *mInstance;
}
#endif // !defined( __SINGLETON_H__ )
This allows nifty things like this:
#define gApplication Application::GetInstance()
class Application : public Singleton< Application >
{
public:
Application();
~Application();
void Run();
int mReturnCode;
};
int main() {
Application app;
// Program logic...
// Now, you can use gApplication anywhere in the program
// (assuming the class is defined), and it will automatically
// get destructed on program exit
}
So far, this Singleton model has served well for every time I've needed a Singleton. That's not saying I've run into every problem that you can have with a Singleton, I'm just saying that it's a fairly robust design for one.
[edited by - daerid on May 15, 2003 1:21:26 PM]
Topic Locked
This topic has been locked by a moderator. New replies are not allowed.
Sign in to reply to this topic.
Advertisement