Silver
Silver

Reputation: 406

Is there a different between these GetInstance() function?

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?

Upvotes: 1

Views: 93

Answers (3)

Silver
Silver

Reputation: 406

I will try to summarize all the comments
So there is many differences between 2 version.

static T* version static T version
memory location heap stack
thread safe yes yes
null possible? no, if new failed, there will be an exception throw no
destructor call on main exit no yes
performance cost of heap allocation low cost of performance
when the memory is freed? after the program end and kernel take back its resource at main exit
when should we use If you need a lazy allocation for memory optimization The memory is allocated at compile time. So use this when you are sure that the singleton has a use in the code

So by the table, static T version seem to be superior in many way.

Upvotes: 1

tedtanner
tedtanner

Reputation: 695

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 (dynamic memory). 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.

Upvotes: 0

K.R.Park
K.R.Park

Reputation: 1139

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.

Upvotes: 0

Related Questions