samedi 31 octobre 2015

Valgrind through Memory leak if Singleton object is not deleted? [duplicate]

This question already has an answer here:

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:

  1. It will give global access to an object, and
  2. It is guarantee that no more than one object of this type can ever be created

My questions are:

  1. How can I deleted the allocated memory done on heap by new operator because my valgrind through as memory leak?
  2. How to call a destructor of class when object stay in heap?
  3. Can I use stack object instead of heap object?
  4. 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