How destructor is executed here?

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
#include<iostream>
using namespace std;


class singleton
{
     int a ;
     
     static int count;
     //static singleton*ptr;
       
    singleton():a(0)
    {
    
    }
    ~singleton()
    {
        cout<<"I am in destructor"<<endl;
    }
public:    
    void display()
    {
         cout<<"a is "<<a<<endl;
         
    }
    
  
static singleton* createinstance()
   {
      if(count==0)
      {  static singleton instance;
      return &instance;
      }
      
      else
      {
          cout<<"Sorry one instance is already created"<<endl;
          return NULL;
      }
   }
  
};
/
int singleton::count=0;
int main()
{
       singleton*ptr=singleton::createinstance();
     ptr->display();      
       return 0;
       
}


Hi All I was going singleton design pattern and wrote the above program and executed and output is
a is 0
I am in destructor


I am really clueless why ptr destructor is called here,am really getting mad with this output.how destructor came into picture?,Please help

Thanks
Prasad
Last edited on
Please use code tags when posting code, to make it readable:

http://www.cplusplus.com/articles/jEywvCM9/
I think the distructor is being called after main() has returned.
Checkout:
http://stackoverflow.com/questions/2204608/does-c-call-destructors-for-global-and-class-static-variables

Seems like the standard says that the destructor is called for static objects after returning from main() or when exit() is called.
Topic archived. No new replies allowed.