I know this is a very stupid question about a singleton circuit, but still this is the interviewer's first choice. Could you tell me the code snippet below.
(1) After deleting the singleton object, why can I still call the show () method and it works fine.
delete obj; obj=NULL; obj->show();
(2) After creating the obj1 object, why can't I print the contents of the gets_lock and release_lock functions, even the printed βone timeβ application will be printed once, and if we increase counter i, and instead of 2, it will print only 1, why?
Foo *obj1=MySingleton<Foo>::GetInstance();
(3) using unique_ptr with a singleton object will have any negative consequences.
code snippet:
#include <iostream> #include <fstream> #include <memory> #include <string> using namespace std; static int i; class Lock { public: Lock(){}; ~Lock(){}; void acquire_lock() { cout<<"aquired lock for class"; } void release_lock() { cout<<"released lock for class"; } }; class Foo { public: void show() { cout<<"\ndone\n"; } }; template <class T> class MySingleton { protected: MySingleton() {} private: //holds one and only object of MySingleton static T* m_pOnlyOneInstance; MySingleton(const MySingleton <T> &) {}; MySingleton <T> & operator=(const MySingleton <T> &) {}; ~MySingleton() {}; public: static T * GetInstance(); void foo() { cout<<"Mohan"; } }; template <class T> T* MySingleton<T>::GetInstance() { Lock lock; if (m_pOnlyOneInstance == NULL) { lock.acquire_lock(); cout<<"one Time"<<endl; i++; if(m_pOnlyOneInstance == NULL) { m_pOnlyOneInstance = new T(); } lock.release_lock(); } return m_pOnlyOneInstance; } template <class T> T* MySingleton<T> :: m_pOnlyOneInstance=NULL; int main() { //std::unique_ptr <Foo> obj (MySingleton<Foo>::GetInstance()); Foo *obj=MySingleton<Foo>::GetInstance(); //obj->show(); delete obj; obj=NULL; obj->show(); cout<<"\ncalling again\n"; Foo *obj1=MySingleton<Foo>::GetInstance(); obj1->show(); cout<<"i="<<i; return 1; }
Note. A lock-related function is only a dummy implementation.
source share