如果没有删除Singleton对象,Valgrind通过内存泄漏?

时间:2015-10-31 12:10:20

标签: c++ design-patterns singleton

我刚刚进入C ++中的创作设计模式,我选择从Singleton类开始。我经历了许多在线教程,发现单身人士可以为我做的是:

  1. 它将提供对象的全局访问权,并且
  2. 保证不能创建多于一个此类型的对象
  3. 我的问题是:

    1. 如何删除新运算符在堆上完成的已分配内存,因为我的valgrind通过内存泄漏?
    2. 当对象停留在堆中时如何调用类的析构函数?
    3. 我可以使用堆栈对象而不是堆对象吗?
    4. 我可以通过实时示例来考虑单例类的任何可视化示例吗?
    5. 以下是我的代码。请帮我理解。

      #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
      
             }
      

0 个答案:

没有答案