-4

This code should be enough for restricting only one instance of singleton class. How can we make two instances of this object?

class Singleton
{
private:
    Singleton()
    {}
    ~Singleton()
    {}
    static Singleton * ptr;
public:
    static Singleton * CreateObject()
    {
        if (!ptr)
            ptr = new Singleton;
        return ptr;
    }
    static void freeObject()
    {
        if (ptr)
        {
            delete ptr;
            ptr = 0;
        }
    }
};
Singleton * Singleton::ptr = 0;
Duncan
  • 92,073
  • 11
  • 122
  • 156

3 Answers3

1

The singleton pattern is about not having two instances of a class.

The easiest way to get rid of that constraint... is to remove the singleton pattern:

class Singleton
{
};

Singleton one = new Singleton();
Singleton two = new Singleton();

As a side-effect, you just made your code cleaner, too, as Singleton is considered an anti-pattern by many.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
1

Well, another possibility not yet exposed is the cuncurrency. That singleton pattern is not secure enough. If you have two (or more) different threads calling simultaneously the CreateObject() method they could easily get different instances of the object.

You should add a mutex to secure that pattern. Or move to another pattern like this one:

 static Singleton& instance()
 {
   static Singleton INSTANCE;
   return INSTANCE;
 }
Federico
  • 743
  • 9
  • 22
-4

This code should be enough for restricting only one instance of singleton class.

It is not.

How can we make two instances of this object?

With the singleton implementation you gave in your question, it is fairly easy to create a second instance:

Singleton* s1 = Singleton::CreateObject();
Singleton* s2 = new Singleton(*s1);

And enjoy memory leaks.


To fix your singleton, you should respect the rule of five (if you define at least one constructor, define all five of them). Or you could use something else than a singleton.

YSC
  • 38,212
  • 9
  • 96
  • 149