Alex Rivera | Logout

C++ singleton vs completely static object

Asked 2010-10-01T16:14:48.137
47

Let say we need to have just one instance of some class in our project. There are couple ways of doing it.

I want to compare. Please can you review my understanding.

1) Classical Singleton pattern

2) Completely static class (all methods and members are static).


As I understand the differences are following:

a) The order of initialization of static members across different units isn't defined. So, completely static members initialization can't use any static members/functions from other modules. And singleton doesn't have this problem.

b) We have to deal with threading for getInstance() of Singleton. However, completely static class doesn't have this problem.

c) Access to methods looks a little bit different. Foo::bar(); vs Foo::getInstance()->bar(); Generally, singleton can return NULL to identify that there were some problems with construction of object and static class can't.

d) Definition of class looks a little bit clunky with bunch of statics for static class.

Have I missed anything?

Edit
Report

1 Answer

1

Let say we need to have just one instance of some class in our project. There are couple ways of doing it.

A better solution:

A variable in main that you pass as a parameter to all required functions would be another.

a) The order of initialization of static members across different units isn't defined. So, completely static members initialization can't use any static members/functions from other modules. And singleton doesn't have this problem.

Singletons do have this problem if their constructor/destructor access other global static lifespan variable.

b) We have to deal with threading for getInstance() of Sigleton. However, completely static class doesn't have this problem.

Not really a problem is it? If you are aware of it just add the appropriate locks in the code.

c) Access to methods looks a little bit different. Foo::bar(); vs Foo::getInstance()->bar(); Generally, sigleton can return NULL to identify that there were some problems with construction of object and static class can't.

I would make my getInstance() return a reference. Then there is no ambiguity over if the pointer is NULL. It either worked or threw an exception. Also this leads to a design where the destruction is correct called on the instance (Don't take this as advice to use Singleton I would avoid it if possible (but if you do use make it neat)).

d) Definition of class looks a little bit clunky with bunch of statics for static class.

No clunkier than writing a singleton properly.

The problem with both these methods is that they are both accessing global mutable state and thus the use of these 'single instance' objects by other objects is hidden from the user. This can lead to problems with testing (TDD requires the ability to mock external functi

answered 2010-10-01T16:58:20.530

Your Answer