Difference between Singleton implemention using pointer and using static object

Posted by Anon on Stack Overflow See other posts from Stack Overflow or by Anon
Published on 2012-10-24T10:38:43Z Indexed on 2012/10/24 11:01 UTC
Read the original article Hit count: 509

Filed under:
|
|

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
};

© Stack Overflow or respective owner

Related posts about c++

Related posts about design-patterns