2

I just want to know when should I use singleton class over static object and vice versa. Because same can be used to have only one instance. One reason I can guess about the storage difference in memory. Is there any other reason to choose one over the other.

5
  • In many cases a singleton is in fact implemented as a class with a static variable. In a multithreaded environment i believe the current c++ standards do not ensure that implementation is valid.. in any other case you can use the "static" implementation: stackoverflow.com/questions/1008019/c-singleton-design-pattern Commented Dec 29, 2013 at 19:47
  • You should not use either! If you absolutely have to you are probably better off using a function local static object. Commented Dec 29, 2013 at 19:47
  • @DietmarKühl: a function local static object = Meyers' singleton. ;-) Commented Dec 29, 2013 at 19:49
  • @Cheersandhth.-Alf: int& f() { static int rc{}; return rc; } - this makes int a singleton of some sort...?!? Commented Dec 29, 2013 at 19:52
  • @DietmarKühl: yep. it's called "Meyers" after Scott Meyers. the main problem with it is that for class type it may be destroyed too soon, e.g. a logging facility releasing itself before some crucial stuff is logged after exit has been initiated. in c++03 it also had threading issues, see stackoverflow.com/questions/1661529/… oh, thinking about it probably still has threading issues... Commented Dec 29, 2013 at 19:54

2 Answers 2

1

The main difference between a singleton and a static object is that the singleton guarantees that there can only be one instance of a particular class type, whereas a static object is only a single instance of a particular type. This means that the fundamental difference is whether it makes sense for the class to have multiple instances or not. For example, let's say that you have a factory that builds widgets.

class WidgetFactory {
    public:
        int numberOfWidgetsBuiltInTheWholeApplication();
            // returns number_of_widgets_built
        std::shared_ptr<Widget> build();
            // increments number_of_widgets_built
    private:
        size_t number_of_widgets_built;
};

Let's also assume that we want to guarantee that we can determine the number of Widgets that were created in the entire application, and enforcing that there is only one WidgetFactory is an easy way to do this. This is where we would use a singleton. If we were to just use a static object, like this:

WidgetFactory& theWidgetFactory()
{
    static WidgetFactory widget_factory;
    return widget_factory;
}

we would have no guarantee that theWidgetFactory().numberOfWidgetsBuiltInTheWholeApplication() was actually the real total, since someone else could come along and make their own WidgetFactory instance.

However, if we make WidgetFactory be a singleton, we now have that guarantee. We could do that perhaps by making the constructors private:

class WidgetFactory {
    public:
        int numberOfWidgetsBuiltInTheWholeApplication();
        std::shared_ptr<Widget> build();
    private:
        WidgetFactory();
        WidgetFactory(const WidgetFactory &); // not implemented
        friend WidgetFactory& theWidgetFactory();
};

Now only theWidgetFactory() function is allowed to create the instance. There are other ways that we could make numberOfWidgetsBuiltInTheWholeApplication() function properly without using a singleton, but perhaps in some situations that solution is more complicated or has other downsides.

Sign up to request clarification or add additional context in comments.

2 Comments

Vaughn. If I want to restrict that only 5 objects can be created of this class. then what will be the approach?
@vivekjain: One approach would be to have 5 friend functions, where each one returns one of the five instances.
1

where only static initialization is involved, a global constant is ok. where dynamic initialization is involved, you want to avoid the static initialization fiasco. hence if you must, singleton should be preferred.

however, mutable singletons are generally just global variables in disguise.

therefore, to the extent practically possible, avoid them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.