And just a little food for thought:
Code:
template < typename Class >
struct Singleton
{
Singleton( void )
{
if( instance_ )
throw; // or what have you...
instance_ = ( Class* )this;
}
static inline Class& instance( void )
{
return *instance_;
}
static inline bool exists( void )
{
return instance_ != 0;
}
virtual ~Singleton( void )
{
instance_ = 0;
}
protected:
static Class*
instance_;
};
template < typename Class >
Class*
Singleton< Class >::instance_ = 0;
And then:
Code:
/*
What the client code sees
*/
class ApplicationManager : public Singleton<ApplicationManager>
{
public:
~ApplicationManager(void)
{ }
virtual void foo( void ) = 0;
protected:
ApplicationManager(void)
{ }
};
/*
The *real* implementation
*/
class MyApplicationManager : public ApplicationManager
{
public:
MyApplicationManager(void)
{ }
virtual void foo( void )
{
cout << "MyApplicationManager" << endl;
}
};
MyApplicationManager
mgr_;
And from the client code:
Code:
int main( void )
{
ApplicationManager::instance( ).foo( );
}
The point is, you don't have to fool with wierd allocation schemes if you don't want to, and you can reassign the singleton by allowing the current one to go out of scope, or if it was dynamically allocated, deleted first. But at any rate the client code doesn't have to worry about how the singleton is managed internally - the code stays the same for them.