This question already has an answer here:
- Properly deleting a singleton 5 answers
I just entered into to creational design pattern in C++, in which I selected to start with Singleton class. I went through many online tutorial and find that what singleton can do for me are:
- It will give global access to an object, and
- It is guarantee that no more than one object of this type can ever be created
My questions are:
- How can I deleted the allocated memory done on heap by new operator because my valgrind through as memory leak?
- How to call a destructor of class when object stay in heap?
- Can I use stack object instead of heap object?
- Any Visual example for singleton class that I can think of with real time example?
Below is my code. Please help me to understand.
#include<iostream>
using namespace std;
class hello
{
public:
static hello *OneObj;
static hello *MakeOneObject(); //funtn with return static class obj
private:hello()
{
cout<<"One Object created"<<endl;
}
~hello()
{
cout<<"Object deleted"<<endl;
}
};
hello* hello::OneObj=NULL;
hello* hello::MakeOneObject()
{
if(OneObj==NULL){
cout<<"in if"<<endl;
// hello OneObj; why stack object not possible?
OneObj=new hello();
}
return OneObj;
}
int main()
{
hello *h,*jj;
h=hello::MakeOneObject();// created
jj=hello::MakeOneObject(); // not created
}
Aucun commentaire:
Enregistrer un commentaire