static T& GetInstance()
{
static T* instance = new T();
return *instance;
}
static T& GetInstance()
{
static T instance;
return instance;
}
Is there any different in these two methods of GetInstance? (except that one will be allocated in heap, one in stack)
Which one is better practice?
CodePudding user response:
The main difference is that in the first implementation, you have no valid way to delete
the T* instance
, resulting a memory leak.
On the contrary, second one will be properly deleted when the program ends : What is the lifetime of a static variable in a C function?
Therefore, I suggest the latter practice when you progrm the Singleton in general.
CodePudding user response:
Yes, there is a difference. In the first function, a pointer is stored in the static area and the T
object is stored on the heap. In the second, the T
object is stored in the static area.
The second function is better by pretty much any metric (with one extremely rare exception I mention below). There are two reasons for this:
First, the first function allocates a T
object behind a pointer but returns the dereferenced value at that pointer. That means that you have (sort of) lost your handle on that piece of memory so you can never deallocate it. It is declared as static
so at least it won't allocate new memory each time the function is called, but it is still not a great idea.
Second, heap allocations are expensive in terms of performance (when compared to storing something in the static area or on the stack). It is generally good practice to avoid heap allocations unless you need heap allocations.
The only case I can think of where you might want to use the first function (assuming it is revised to not leak memory) is if a T
object is too large to fit in the static area. It would have to be really large indeed, but it is a possible scenario.