I know 2 methods to make singleton pattern like this:
class sgt_static
{
sgt_static() { }
public:
static sgt_static* get_instance()
{
static sgt_static instance;
return &instance;
}
}
and this:
class sgt_new
{
sgt_new() { }
public:
static sgt_new* get_instance()
{
static sgt_new* instance = NULL;
if ( instance == NULL ) instance = new sgt_new();
return instance;
}
}
I knew some differences between them:
- Instance of
sgt_newshould be delete by myself. - If the program exits(normally), instance of
sgt_staticwould be delete by program itself(or by OS?).
But I set breakpoints in ~sgt_new(), when my program exits, debugger has no any breaking action at all. Someone says that OS would reclaims these resources back. Is that true ? So, instance of sgt_new won’t lead to any memory leak?
Aparts from points above of my list. Are other differences between 2 implementation of singleton?
Objects on the heap are not deleted by the C++ system unless something calls
delete. That is, the object in your second version won’t get destroyed. Depending on how the object is used this may be quite intentional: While wrapping the object with a function guarantees that the object won’t be acced before it is constructed there is mothing which can be done that it is accessed after it has been destroyed. After all, there is no control to where the pointer got passed.When a program terminates, for whatever readon, the resources are reclaimed from outside the program. When and how this is done depends on the operating system and differnt resources may be reclaimed at different times. Note that this resource clean-up does not call destructors but merely makes resources like file descriptors (or equivalent), memory, locks, etc. available. That is, if your singleton’s destructor has any important object you probably want to use the first approach.
That said, singletons are massively over-used as some sort of suspected to be glorified global memory! The are a few legitimate uses of singletons but probability indicates
your case is not one of them: less than 1% of singleton uses are legitemate based on my running count. The way to determine if a singleton is to determine if it could be conceivable if two (or more) versions of the program running in the same executable still can use the same singleton. If not, it is not a legitemate use of a singleton.