How to fix leaking this in constructor

111 Views Asked by At

i have a class

class Foo { 
   private static Foo foo_obj = null;

   public Foo() {
       if (foo_obj == null) {
           foo = this;
       }
   }
}

I get a warning about leaking this, how would i go about fixing it.

1

There are 1 best solutions below

0
Jeanne Boyarsky On

It looks like you are trying to use the singleton pattern. It's an odd way of doing it though and doesn't work. Because each time Foo() gets instantiated, you create a new one. Why not use a more traditional approach like:

class Foo { 
   private static Foo foo_obj = new Foo();
   private Foo() {}
   public static Foo getInstance() { return Foo(); }
}

There are many variations of this pattern on wikipedia.