Game Development Reference
In-Depth Information
static T instance;
return instance;
}
protected:
singleton() {}
singleton(const singleton&) {}
singleton(const singleton&&) {}
singleton& operator = (const singleton&) { return *this; }
};
Thissingleton implementation ismeanttobeusedasabaseclassforanyobjectwewishto
make a singleton.
Calling Singleton::Get() givesyouareferencetotheoneinstanceoftheobject,thefactthat
the constructor, copy constructor and assignment operator are private makes it impossible
for the singleton to be instances multiple times.
One of the most significant problem with this implementation is controlling the lifetime
of such a singleton. First, the singleton will be constructed on the first Singleton::Get()
call, depending on what it does on construction, if it has dependencies on any resources, it
would need to ensure they are ready and available but it has no way to guarantee it. The
next significant issue is if the singleton creates or references any resources, it will need to
release them and itself at the right time. In a large game engine, this is not always as clear
cut,manyresourcesoftenhavedependenciesthatmustbereleasedatdifferentstagesofthe
pipeline.Finally,thisimplementationisnotthreadsafe,asingletonimpliesglobalaccess,it
is conceivable that a user may unknowingly try to access a singleton from different threads
and run into problems with resources that may not be available when expected. There are
strategies to deal with all of these problems, but this results in a more complex singleton
pattern implementation.
So in conclusion, beware of singletons, in game development they are often overused and
rarely robust enough to handle many of the complex situations that arise often in game
code.
For a very thorough description of singletons and how to address many of the complexities
that we run into when using them, see (Alexandrescu, 2001).
Search WWH ::




Custom Search