What a pity! Because of being too nervous, I made mistakes on this little test! However, it’s really not a very relaxed atmosphere for me, and bad time for test! The problem is about,
“Please design a Singleton mode template for a class .”
When the interviewer checked my paper, he tipped me that my program can not guarantee only one instance of class, but my brain were thoroughly in a null at that time and didn’t get any better changes.
Now, I give my whole codes corrected as a lesson.
template<class T>
class Singleton
{
public:
Singleton()
{
}
virtual ~Singleton()
{
}
static T* create()
{
pthread_mutex_lock(&_mutex);
if (me == NULL)
me = new T;
pthread_mutex_unlock(&_mutex);
return me;
}
static void destroy()
{
pthread_mutex_lock(&_mutex);
if (me != NULL)
{
delete me;
me = NULL;
}
pthread_mutex_unlock(&_mutex);
}
private:
static T* me;
static pthread_mutex_t _mutex;
};
template<class T>
T* Singleton<T>::me = NULL;
template<class T>
pthread_mutex_t Singleton<T>::_mutex = PTHREAD_MUTEX_INITIALIZER;
My test class and other codes are here,
class A
{
public:
A()
{
Foo();
}
private:
void Foo()
{
std::cout << this << std::endl;
}
};
int main()
{
A* pa = Singleton<A>::create();
A* pb = Singleton<A>::create();
Singleton<A>::destroy();
return 0;
}
class A is the test object, and in its constructor, its address will be printed. Unless “destroy()” function is called, ”Foo()” function will only be called once in this Singleton mode. In the end, I remembered my faults in the interview mainly was – do not use “static” for function “create” and “destroy” in Singleton template class, of course the same problem for private member “me” and “_mutex”.
I’m really not an active tester, but active doer.