One other option, if you don't want to code a singleton and polymorphism is not required, is to enclose the public functions in a namespace and declare the private functions and data in an anonymous namespace within the source file.
i.e.
.H
Code:
namespace My_Api
{
void Function2();
}
.CPP
Code:
// Private functions and data.
namespace
{
int a;
int b;
void Function1()
{
// Stuff
}
}
// Public functions and data.
void My_Api::Function2()
{
a = 0;
Function1();
}
"It doesn't matter how beautiful your theory is, it doesn't matter how smart you are. If it doesn't agree with experiment, it's wrong."
Richard P. Feynman
I will prefer to deal with one static object and many non static field as like singelton than many objects who happend to work on many static field through their member functions.
I mean should not we be trying to cut down on usage of static when we are programming in object oriented language.
Regards
Prashant.
Dont forget to rate my post if you find it useful.
This is an old argument, but I thought I'd throw in my 2c. (I am Australian so I use 's' instead of 'z' in my spelling )
I consider the main points of a singleton class to be:
1. Guaranteed single instance only.
2. Ownership isn't obvious, so it looks after its own construction/destruction - lazy evaluation.
If these points are important to you, then use the good old create-on-first-use + static-member-variable + getInstance() function. There is nothing really wrong with it.
Some argue that this causes a pointer check (which can be inlined if the code is in the declaration file so not a real issue) and an indirection (pointer deference) for every call, which isn't as efficient as a direct call - especially when you know the thing is basically static. If you're going to go into a tight loop and call lots of functions off a class built like this, then do the getInstance() once into a pointer before the tight loop and then it just becomes a normal function call. No big deal, I'm sure you've got bigger fish to fry in your code than pointer dereferencing! Oh, and if you're going to allow multiple threads, please be careful and make sure the getInstance() function is protected!
On the other hand, I -personally- don't like lazy-evaluation of construction 99% of the time. I fall into the camp of explicit initialisation/construction. I could argue why, but that would be another thread
I come from game programming which tends to have a lot of Factory-type singletons: Core, Input, Renderer, Networking, I/O, Object creation Factory etc. These are all typical examples of singletons, in my work. They also typically require more sophisticated construction than the default constructor, so invariably have an init(blah, blah, blah) function. It's at this point I tend to diverge from the typical singleton pattern theory (because point 2 isn't important to me).
There are two options I can use:
1. Create a namespace and put all static functions (no data) in it, with everything else in the implementation file (.cpp). Have an explicit init()/uninit() pattern with ownership by the owning system, typically the application itself. This gets single instance, encapsulation, explicit construction (and destruction let's not forget!) and all calls are statically linked direct address calls.
2. Same as 1 but use a class instead of a namespace. If I do this, I make the constructor and destructor private, sending a message to readers of the class that it can't be derived or constructed on the stack/heap by any other class other than itself (single instance again). Note that like 1, all data is kept in the implementation file. Same benefits as 1 really, but some don't like the idea of a class having all static functions - they feel it's not very OOP, which I guess is true in that a purely static class is more a grouping of functions (i.e. namespace) than an instance of an object.
So, I tend to prefer the namespace approach. It's still called the same way as a static function in a class - MyClass::someFunc() - but doesn't confuse OO people who freak out seeing an all-static class
Keep in mind that the private data, held in the implementation file remember, is in a kind of uninitialised stated, and that the user of the namespace/class has direct function call access which means if they forget to call init() obviously there will be a problem. It's usually pretty obvious if this happens (instant crash on first function call ). Also, I honestly think that good programmers should know the how and the order in which they are creating their system, so it doesn't hurt to see all the inits done in a nice big block at the start.
And always keep in mind that with an explicit initialiser you get to brace it with an explicit uninitialiser. This is very useful, and allows you to check all sorts of things before exiting an a application, in a specific order - not some random initialised order like a lazy-evaluation method.
One last point: threading. Again, you REALLY want to protect the getInstance() function against multiple threads potentially creating the singleton. Beware! This is another reason I like the explicit initialisation pattern. I use this pattern on consoles like the PS3 so I darn well know when a singleton is created and destroyed.
class Something
{
public:
static Something& Instance();
private:
Something();
};
Something& Something::Instance()
{
static Something singleton; // will be constructed when
// the function is called
// for the first time.
return singleton;
}
As aready suggested here, implementing singletons is not quite a simple task as it seems to be.
I kindly recommend reading about singletons in Modern C++ Design By Andrei Alexandrescu.
Then think twice...
Additionally, I have attached here a simplified example about how a class intended to be singleton becomes a kind of "doubleton".
Well the cause is quite easy to be found and somebody may ask "Is it possible? Who did such a stupid thing?...". The answer is "Yes, in practice is possible... done by some wise super-architect, sleeping with GoF under his head".
I agree with the exceptions-in-destructor point. I don't use exceptions in my line of work, so I need to have an explicit init(), which has the benefit of me knowing exactly when my singleton is created.
Another point I forgot to mention before, is the problem of memory allocation and lazy-evaluation when you're working inside a fixed memory system. Allocating a potentially large block of singleton/never-moving block of memory at some arbitrary point can effectively create a permanent split in memory. Consider this: you're application starts up and begins allocating it's objects, goes into a level (if you're a game), allocates some more stuff, which then all gets freed up nicely when you leave, then boom, you call some function to a singleton (maybe a function to a network manager to upload your highscores somewhere) for the first time, and it allocates a piece of memory on-first-use, which never moves. That just permanently reduced your maximum potential allocation block. Not nice if you're on a system like a PS3/Xbox360. This is why you create/init your permanent blocks of memory up front, right next to each other.
On a side note, look at the complexity of the Singleton class in Andrei Alexandrescu's book. It goes from being a fairly simple request of a single instance of something, lazily-evaluated, to a nightmare very quickly (order of creation/destruction/thread safety). It's over-engineering to the extreme for 99% of cases, IMHO.
I'll stick to my namespace-singleton method. Simple, hides data, single instance, known allocation pattern. If anything, it's just like coding in pure C (i.e. no class. I can see a joke here: "You're like C baby... no class")
Just an aside note about exceptions-in-destructor: it's "nice" when dealing with whatever static analysis tool (in conjunction with a strong QA department ) which complains that if you have any function call in the destructor, it's mandatory to catch potentially thrown exceptions.
As a result you can see "well written" destructors like
Code:
CFoo::~CFoo()
{
try // Just to make the QA happy.
{
::DeleteCriticalSection(&m_cs);
}
catch(...)
{
// Not even Chuck Norris can catch an exception here. :-)
}
}
Even a try-catch block in a destructor is not enough - if the destructor is called due to an exception being thrown and it then somehow throws its own exception, we suddenly have two active exceptions at the same time (long before the catch block is encountered).
Also, DeleteCriticalSection is declared as extern "C" and the checking tool should therefore know that it never throws an exception, and C++ functions can have the no-throw declaration on their signature.
Originally Posted by Shane Stevens
Another point I forgot to mention before, is the problem of memory allocation and lazy-evaluation when you're working inside a fixed memory system. Allocating a potentially large block of singleton/never-moving block of memory at some arbitrary point can effectively create a permanent split in memory.
That is a good point. One workaround would be to manually access all the problematic singletons at application startup.
Last edited by Zaccheus@Work; April 24th, 2009 at 03:47 AM.
Also, DeleteCriticalSection is declared as extern "C" and the checking tool should therefore know that it never throws an exception, and C++ functions can have the no-throw declaration on their signature.
Unfortunately, sometimes Chuck Norris doesn't know that (see the comment from catch block ).
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.