I have a class with a static factory constructor which returns a pointer to the object created.
I have to declare the object as a static object inside a namespace but I don't know how to delete it correctly
class Foo
{
public:
Foo(int, int* );
virtual ~Foo();
static Foo* MyFooInitializer(int n )
{
int *p = new int[n];
for (int i=0; i<n; i++)
p[i]=i;
Foo *ret = new Foo(n,p);
delete p;
return ret;
}
int someFooFunction(int a);
}
Then in my namespace I have a static inline
function
namespace MyNamespace
{
static inline void myfunction()
{
static Foo *foo1 = Foo::MyFooInitializer(10);
int y = somevalue();
int x = foo1->someFooFunction(int y);
}
}
I obviously have a memory leak here because the object is never deleted.
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).
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.
SOLUTION:
I modified the body of MyFooInitializer
this way:
static Foo* MyFooInitializer(int n )
{
int *p = new int[n];
for (int i=0; i<n; i++)
p[i]=i;
static Foo ret = Foo(n,p);
delete[] p;
return &ret;
}
This allows me to release all the memory correctly when the program terminates. Valgrind says all the heap memory is freed!
There is no need for allocating that Foo on the heap here:
static Foo* MyFooInitializer(int x) {
static Foo some_foo(x);
return &some_foo;
}
There are no leaks in that code, that Foo will be destroyed when your program ends.
Note that if the pointer returned by MyFooInitializer
actually points to some class which inherits from Foo
, then you'd just have to use the derived type for the static variable:
static Foo* MyFooInitializer(int x) {
static SomeFooDerived some_foo(x);
return &some_foo;
}
Edit: Since you provided the actual function body, my answer is valid. You'd do it like this:
static Foo* MyFooInitializer(int n ) {
// Don't know what this p is, anyway...
int *p = new int[n];
for (int i=0; i<n; i++)
p[i]=i;
static Foo ret(n,g); // what is g?
delete[] p; // smart pointer plx
return &ret;
}