Reputation: 5526
I am sure this could have been answered but I couldn't actually find a consolidated answer.
what are the problems with the following singleton that is just a function and guaranteed to have initialization and assuming T supports operator!, needed constructors, functions etc? (I am not looking for thread safety). More over, its ok for others to create objects of T as T in my case is a database handle I want to use for the life of my program.
template<typename T>
T* getInstance(){
static T instance;
if ( !instance && !instance.initialize() ){
return NULL;
}
else {
return &instance;
}
}
Upvotes: 1
Views: 106
Reputation: 5805
There are some mistakes in your code -- the template type is being used instead of the variable.
For what you need (don't care about thread safety & need it for the entire duration of your application), it might be exactly what you need. You might wish to start from this though:
template<typename T> T* getInstance()
{
static T instance;
return &instance;
}
Upvotes: 1
Reputation: 10280
This won't even compile. Moreover, using singletons will get you in trouble sooner or later. For instance, when will you destroy the instance? In C++ it is generally better to be explicit about construction and destruction. Lookup the static gateway pattern (example in C#).
Good luck!
Upvotes: 0