Alex Rivera | Logout

Singleton - Why use classes?

Asked 2009-09-08T13:46:35.887
16

Just the other day I have seen code that uses the so called singleton pattern. Meaning something along the lines of

class MySingleton{
public:
    void foo() { ... }
    static MySingleton&get_instance(){
        static MySingleton singleton;
        return singleton
    }
private:
    MySingleton(){ ... }
    ~MySingleton(){ ... }
    int bar;
};

I do see why one would want to do that:

  • Make the instance globally accessible.
  • Make sure that there is never more than one instance of that class.

However I do not see why this way of doing things is superior to a couple of free functions. The way I'd implement it is to put

namespace some_name{
    void foo();
}

in the header and

namespace some_name{
    void foo(){
        ...
    }
}

in the implementation file. If I need initialization and/or cleanup I either add a couple of functions that must be explicitly called or I add

namespace{
    class Dummy{
        Dummy(){ ... }
        ~Dummy(){ ... }
    }dummy;
}

into the implementation file.

I know that this is from a semantic point of view a singleton, however I see the first variant used far more often in C++ Code than the second. Why? I consider the second version to be slightly superior, so I asking myself if I'm missing something obvious.

  • The second version is simpler to implement and less error prone. In the first variant the private copy constructor is missing on purpose to demonstrate this. In the second variant there is no way to do this error.
  • Implementation and interface are better separated in the second version. In the first all private members must be declared in the header. This has the advantage that you can rewrite the implementation from scratch and don't even need to recompile anything that uses the singleton. When using the first variant it is ve
Edit
Report

1 Answer

4

does this help?

What is so bad about singletons? http://steve.yegge.googlepages.com/singleton-considered-stupid

Rephrased: A singleton is a glorified global, so just 'implement' it as a global.

answered 2009-09-08T13:54:29.323

Your Answer