The Singleton
The Singleton
In most cases for a software codebase there is the need to usually ensure that there
is one single instantiation of an object. In other words, usually a fairly important object
which would wreck havoc on the application if there were more than one.
In the days of C, this was accomplished with the use of a global variable. While
not pretty, it does do the job it is meant for. One problem with using a global variable
this way, is that the object is always consuming resources. For example, what
if we have a class design in which the Singleton object need only be created when
certain circumstances / conditions are met?
In the C++ language, we can create a small Singleton object that we can
then use for future objects in our system. In other words we can create a base
object to generalize any common handling of Singletons.
Da Code!
/** * Template class for creating single-instance global classes. * The code in this file is taken from article 1.3 in the the book: * Game Programming Gems from Charles River Media with the * copyright notice going to Scott Bilas. */ templateclass ISingleton { protected: /** The static member object */ static T* ms_Singleton; public: /** * Constructor */ ISingleton( void ) { assert( !ms_Singleton ); ms_Singleton = static_cast< T* >( this ); } /** * Destructor */ ~ISingleton( void ) { assert( ms_Singleton ); ms_Singleton = 0; } /** * This method just returns the internal member by * reference * @return T& - reference to internal abstract Type */ static T& getSingleton( void ) { assert( ms_Singleton ); return ( *ms_Singleton ); } /** * This method just returns the internal member by * a pointer * @return T* - pointer to the internal abstract Type */ static T* getSingletonPtr( void ) { return ms_Singleton; } };
That’s pretty much all we need defined for our lowest-level base class.
To see this object in use, be sure to check out the other tutorials
on this site. Most of them employ this Singleton object to
work with objects such as our FileLogger
Feedback? Comments?
Either comment to this posting, or use our contact form to get in touch with us.











This is default description text on Padangan Themes, of course you can change this text via you profile administration.