Difference between Singleton implemention using pointer and using static object
- by Anon
EDIT: Sorry my question was not clear, why do books/articles prefer implementation#1 over implementation#2?
What is the actual advantage of using pointer in implementation of Singleton class vs using a static object? Why do most books prefer this
class Singleton
{
private:
static Singleton *p_inst;
Singleton();
public:
static Singleton * instance()
{
if (!p_inst)
{
p_inst = new Singleton();
}
return p_inst;
}
};
over this
class Singleton
{
public:
static Singleton& Instance()
{
static Singleton inst;
return inst;
}
protected:
Singleton(); // Prevent construction
Singleton(const Singleton&); // Prevent construction by copying
Singleton& operator=(const Singleton&); // Prevent assignment
~Singleton(); // Prevent unwanted destruction
};