doubt in a singleton factory method

Hi,
I am trying following program
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
$ cat singleton.cpp
#include<iostream>
using namespace std;

class singleton
{
  private:
  static bool instance;
  static singleton* single;
  singleton()
  {
    cout << "Calling singleton's private constructor\n"<<endl;
  }

  public:
  void method()
  {
    cout<<"calling method()\n"<<endl;
  }

  static singleton* getInstance();
 ~singleton()
  {
    cout << "calling singleton's destructor\n"<<endl;
    //delete this;
  }
};

bool singleton :: instance=false;
singleton* singleton :: single=NULL;
singleton* singleton :: getInstance()
{
  cout << "Calling getInstance()\n"<<endl;

   if(false==instance)
   {
     cout << "entering if block\n"<<endl;
     single = new singleton;
     instance = true;
     return single;
   }
   else
   {
    cout << "entering else block\n"<<endl;
     return single;
   }
}

int main()
{
 singleton* sc1, *sc2;
 sc1->getInstance(); //or sc1 = singleton :: getinstance()
 sc1->method();

 sc2->getInstance();
 sc2->method();

 return 0;
}


Here is an output
Calling getInstance()

entering if block

Calling singleton's private constructor

calling method()

Calling getInstance()

entering else block

calling method()



The program works fine but I see that the destructor never gets called. ( I tried deleting the pointer by various methods but didn't succeed.) Could somebody please let me know how would I delete static class pointer(single). Thanks in advance.
closed account (o1vk4iN6)
You never free the memory, create a function in the class that delete's the pointer, than call that at the end of your code.
Why is it a pointer? That's adding so much complexity to the otherwise simple single-threaded singleton:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include<iostream>
using namespace std;

class singleton
{
 private:
  singleton()
  {
    cout << "Calling singleton's private constructor\n";
  }

  public:
  void method()
  {
    cout<<"calling method()\n";
  }

  static singleton& getInstance()
  {
      cout << "Calling getInstance()\n";
      static singleton TheInstance;
      return TheInstance;
  }
 ~singleton()
  {
    cout << "calling singleton's destructor\n";
  }
};

int main()
{
 singleton& sc1 = singleton::getInstance();
 sc1.method();

 singleton& sc2 = singleton::getInstance();
 sc2.method();
}
Calling getInstance()
Calling singleton's private constructor
calling method()
Calling getInstance()
calling method()
calling singleton's destructor


PS: Don't forget to make the copy constructor private, too.
Last edited on
Topic archived. No new replies allowed.