2

How does Destructor work?

 3 years ago
source link: https://www.codesd.com/item/how-does-destructor-work.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How does Destructor work?

advertisements

I did practicals on Destructor but when compile this program I don't know why the output not come as I thought.

#include <iostream>
using namespace std;
class aaa
{
   private:
   static int x;
   int code;
   public:
   /*after constructor executes 3 times the value of "code" becomes 103*/
  aaa()
  {
    code=x;
    cout<<"Default Constructor"<<endl;
    x++;
  }
  ~aaa()
  {
    cout<<"Destructor of "<<code<<endl;
  }
};
int aaa::x=101;
int main()
{
   aaa *p;
   p=new aaa[3];
   delete []p;
   return 0;
 }

Output is:

Default Constructor
Default Constructor
Default Constructor
Destructor of 103
Destructor of 102
Destructor of 101

while I thought it was going to be this:


I don't know why the output not come as I thought.

Because the objets are destructed in reverse order of construction: First constructed, last destructed.

The destructors are called in the reverse order of the constructors' calls, which explains the behavior you see.

So when you dynamically allocate memory with new[] for your array, the constructors are called in the natural order (the one you expect), but when delete[] is called to free that memory, every element of the array gets destructed in the reverse order.

Read more in Why destructors are not called in reverse order for array of objects?


What happens if i write delete p instead of delete []p, so ho many times Destructor is called?

C++ requires that you delete arrays with delete[] and delete non-arrays with delete. So I can't answer that. Read more in Delete and delete [] are the same when deleting arrays?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK