Singletons: to lazy instantiate or not?

Hi everyone.

A book I am reading suggests that it is possible to "lazy instantiate" singletons (i.e. when GetInstance() is called, check if an instance exists, and if so, return it, and if not, create one and return it). The singletons I've actually seen (albeit in Java) do this. But the book decides instead to write a separate Creator() function (i.e. check if an instance doesn't exist, and if not, create one).

However the book is unclear on why it decides to do this: it vaguely says it's "generally cleaner". With their implementation, if Creator() hasn't been called, GetInstance() will return NULL. We don't gain anything performance-wise by not checking whether or not the instance exists in GetInstance(), because it just means whatever code is calling GetInstance() has to handle what happens if the instance is NULL instead.

So can anyone explain to me what the actual benefit of having a separate Creator() function is? Or maybe an example of when we might want a singleton's GetInstance() function to return NULL?
If singleton Creator arguments is not known at program start: For example we do not want to create our singleton until we get some info from web server.

it is possible to "lazy instantiate"
That is the best practice. static object can encounter whole lot problems you would better avoid.
http://www.parashift.com/c++-faq/static-init-order.html
Last edited on
Singletons can be lazy instantiated by making them static inside the function.
1
2
3
4
5
static Object& getInstance()
{
	static Object instance;
	return instance;
}

Not sure what the benefits are the way your book do it. Only thing I can think of is if you want to have more control over when the object is destructed.
Topic archived. No new replies allowed.