title: Static factory methods and static objects memory leaks
body: <p>I have a class with a static factory constructor which returns a pointer to the object created.</p>
  
  <p>I have to declare the object as a static object inside a namespace but I don't know how to delete it correctly</p>
  
  <pre><code>class Foo
  {
     public:
     Foo(int, int* );
     virtual ~Foo();
     static Foo* MyFooInitializer(int n )
     {
        int *p = new int[n];
        for (int i=0; i&lt;n; i++)
           p[i]=i;
  
        Foo *ret = new Foo(n,p);
        delete p;
        return ret;
     }
     int someFooFunction(int a);
  }
  </code></pre>
  
  <p>Then in my namespace I have a <code>static inline</code> function</p>
  
  <pre><code>namespace MyNamespace
  {
  
      static inline void  myfunction()
      {
          static Foo  *foo1 = Foo::MyFooInitializer(10); 
          int y = somevalue();
          int x = foo1-&gt;someFooFunction(int y);
      } 
  }
  </code></pre>
  
  <p>I obviously have a memory leak here because the object is never deleted.</p>
  
  <p>The important fact is that I need that foo1 is declared as static because once created it must be the same object during all the program and must be unique (it keeps track of some variables).</p>
  
  <p>Probably this is a design problem, but I don't know how to delete it when my program exits or when I explicitly want to delete it to reinitialize it.</p>
  
  <p><strong>SOLUTION:</strong></p>
  
  <p>I modified the body of <code>MyFooInitializer</code> this way:</p>
  
  <pre><code>   static Foo* MyFooInitializer(int n )
     {
        int *p = new int[n];
        for (int i=0; i&lt;n; i++)
           p[i]=i;
  
        static Foo ret = Foo(n,p);
        delete[] p;
        return &amp;ret;
     }
  </code></pre>
  
  <p>This allows me to release all the memory correctly when the program terminates. Valgrind says all the heap memory is freed! </p>