monjardin said:
I usually do the following so that you don't have to worry about doing a new/delete on your instance:
class Singleton
{
public:
static inline Singleton& Instance() {
static Singleton instance;
return instance;
}
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
};
The singleton is instantiated the first time you call the Instance() function (I think).
Actually, the singleton is instanced at compile time. When you create a static variable inside of a function, it's initialized onto the data segment, so, as .oisyn says, you don't actually have control over when it's initialized.
That said, what you've got is basically a nice OO-based singleton-ish pattern above, so it's not all bad, but the same thing could be achieved by creating a global and externing it.
Although, if letsay you were tracking access to people acquiring the instance, or doing some sort of locking on access, then the Singleton you have listed could be modified easily to accomplish this.
Where the Singleton really shines, as .oisyn already mentioned, is in controlling construction and deletion, and that's why the Singleton pattern usually has memory allocation involved.
For example, if you have a class A that's used as a singleton, as well as a class B, which is a singleton, you can ensure that any dependencies between the two are reconciled in an appropriate order, at runtime.
That is, things are constructed in the appopriate order, which you can't guarantee with static function variables, or even global variables.
If I'm not making any sense, let me know and I'll post up an example. Otherwise, I think I'll limit my posts to a short story from now on in, instead of a novel. :)