C++ singleton

How to write a class that can only be instancialized once?

what about my implementation below?

#include<iostream>
#include<stdexcept>
using namespace std;

class Singleton
{
public:
 int b;
 Singleton();
private:
    static int num;
};


int Singleton::num = 1;
Singleton::Singleton()
{
    if (num == 0)
        throw runtime_error("Singleton instancialized more than 1 times");
    num--;
}

int main()
{
        Singleton a;
        Singleton b; //here exception occurs
}

The typical schemis is to make the constructor private, and provide a public function that sees if an instance has already been instantiated, constructs it if it's not been, and then returns it. This way, no other class can even attempt to instantiate your class a second time, since the constructor is private. Always better to find out problems at compile-time rather than run-time (IMHO).

but if the user use the public function to instantiate a second time, it can also only be detected at run time. Isn't it?

No - make a private static variable that is a pointer to your object type. Make sure it's NULL initially. Then at each request, check if this pointer is NULL - if it is, then no instance of your object has been initialized, so construct one and return it. If it is non-NULL, just return it:

class Single
{
private:
    static Single *single;  // Initialize to NULL at definition.
    Single();
public:
    static Single *getSingle() {
        if (!single)
            single = new Single();  // Only gets called once, then if() statemenet is false.
        return single;
    }
};

That's good. But what is the backward of my implementation? If I change the static variable num to any other integer such as 3, I can get a class that can only be initialized three times. Isn't it more flexible?

Not quite. That's just hoping your constructor only gets called once.

class Single
{
private:
    static Single *single;  // Initialize to NULL at definition.
    Single();
public:
    static Single *getSingle()
    {
        // if we've already created the singleton, no need to spend the time
        // needed to lock and unlock the mutex
        if ( !single )
        {
            static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

            pthread_mutex_lock( &mutex );

            // need to check again in case another thread created the singleton
            // while this thread was blocked waiting for the mutex
            if ( !single )
            {
                single = new Single();  // Only gets called once, then if() statemenet is false.
            }

            pthread_mutex_unlock( &mutex );
        }
        return single;
    }
};

Just make an array of pointers - though how you'd decide which one to give out is up to you.

Well, it's assuming the class is running in a single-threaded environment, but that brings its own special problems.

This is a fairly well-known anti-pattern - please avoid it. In general, any access to a variable protected by a mutex must be protected by that mutex, or reorderings in (i) the code the compiler generates, (ii) cached memory read/writes in the CPU and (iii) competing caches on SMP systems mean your strategy may break.

In this case, in the line "single = new Single()", the compiler is allowed to reorder the instructions in any way it wants, so it is e.g. allowed to set the pointer 'single' to point to the memory location before it's initialized. In this case, the 'if (!single)' code, if run at a certain point in the other thread's execution, would not wait for initialization, be false, and you're suddenly returning a pointer to a potentially uninitialized structure from your function. Also other things - I understood this (I think) when I was learning this stuff, but even if you can (or think you can) refute this, there are many other reasons.

And besides, how much performance do you really expect to get from this?

Also, things get more complicated on SMP systems, so without propper memory barriers (which locking the mutex would give you) you cannot tell if memory read/writes would be reordered or not.

    static Single *getSingle()
    {
        Single *result;
        static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

        // All accesses to 'single' occur when this mutex is locked.
        pthread_mutex_lock(&mutex);  // Note: Check return value.
        if ( !single )
        {
            single = new Single();  // Only gets called once, then if() statemenet is false.
        }
        result = single;
        pthread_mutex_unlock(&mutex);

        return result;
    }
};

Or, even better, just use the already-supplied pthread_once().

If the pointer is non-null, it's already been modified the one time it's going to get modified so it no longer needs to be protected by locking the mutex and the implied memory barriers

You have not addressed the issues I laid out in my last post with regards to why the above statement is irrelevant. Did you deliberately ignore them, or did I not explain them satisfactorily/did you not understand them?

I was in your position not too long ago - I did not believe the person saying what I am saying now, but I was willing to learn and be proved wrong, so I did some research.

A quick web search revealed that it's called double-checked locking. Have a read of the external links at the bottom of that article (especially "C++ and the Perils of Double-Checked Locking") as well as The "Double-Checked Locking is Broken" Declaration which is very informative.

Moderator comments were removed during original forum migration.

I'm fond of this method....

class Single
{
public:
  static Single &getSingle()
  {
    static Single theSingle;
    return theSingle;
  }

private:
  Single();  // private constructor to enforce singleton

//public:  // (1) if you uncomment this line then (2) below
           //       can be made to compile (and crash!).
  ~Single();
};

Single::Single()
{
}

Single::~Single()
{
}

int main()
{
  Single &s = Single::getSingle();
//  delete &s;  // (2) won't compile if you uncomment unless you
                //     uncomment (1) above; but, who would do this?
  return 0;
}

This has the benefit that the reference can't be freed (though, as I show, the caller can jump through hoops to free it, so the private destructor is still good practice). However, I'd suspect that most people would see a reference and know that deleting it is probably bad.

Buyer beware, however, that the standard is pretty hush-hush on its thread safety. Though, most practical compilers (g++) wrap the local static member ("theSingle") with locks to insure it does not get constructed more than once. In my opinion, this is preferable to roll-your-own. However, if you must, a pthread_once_t control is probably the way to do it as here:

#include <pthread.h>

class Single
{
public:
  static Single &getSingle()
  {
     pthread_once(&onceCtl, BuildTheSingle);
     return *theSingle;
  }

private:
  static Single *theSingle;
  static pthread_once_t onceCtl;
  static void BuildTheSingle();

  Single();
  ~Single();
};

pthread_once_t Single::onceCtl = PTHREAD_ONCE_INIT;
Single *Single::theSingle = NULL;

void Single::BuildTheSingle()
{
  theSingle = new Single();
}

Single::Single()
{
}

Single::~Single()
{
}

Which uses the same reference return to, IMO, instruct the caller that it's not theirs and they shouldn't be free'ing it.

I suppose you could also use auto pointers or something, too, but...this is good enough for me, lol.

edit: for the record, the former implementation is thread-safe in C++0x, as such, in any newer code compiled with C++0x compliant compiler, I'd recommend it to rid all the boilerplate crap and distill it right to only that code which is both sensible and required. Just one man's opinion....