简体   繁体   中英

Why destructor is not called for an array of objects?

I have an array of 10 objects. In the code written below constructor is called 11 times but destructor is called only 1 time. Why constructor is called for array of objects and not destructor?

#include <iostream>
using namespace std;

class A
{
public:
   A()
  {
       cout<<"ctor called"<<endl;
  }

  ~A()
  {
       cout<<"Destructor called"<<endl;
  }

};

int main()
{
    A *a = new A[10];

    A v;
}

Above code prints "ctor called" 11 times and "Destructor called" 1 time, Why so???

You have to delete items allocated with new, it doesn't happen automatically.

int main()
{
    A *a = new A[10];
    delete[] a;
    A v;
}

Now the destructor will be called 11 times.

You need to call delete on the array because it was allocated using new . Ex. delete[] a;

v was allocated locally in the function so the destructor is automatically called at the end of the function.

There is a big difference between these two statements

A *a = new A[10];

A v;

v is a local variable. The compiler itself insert appropriate code to delete this object when the control exits this code block. As for the dynamically allocated array then nobody except you yourself will bother that it was not deleted. When the program finished the operating system simply marks it as free that to be able to give it to other programs. So it is you who should explicitly free this memory using operator

delete []a;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM