Home > Net >  Why destructor is not called when an element in an array is assigned?
Why destructor is not called when an element in an array is assigned?

Time:09-13

#include <iostream>
using namespace std;

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

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

  A& operator=(const A &a)
  {
       cout<<"Copy assignment operator called"<<endl;
       return *this;
  }
};

int main()
{
    A a;
    A aa[2];
    aa[0] = a;
}

3 times default constructor is called; 1 time copy assignment operator is called; 3 times destructor is called.

Question: Shouldn't the destructor be called 4 times?

CodePudding user response:

No, the destructor should be called three times.

There are three objects of type A:

  • one variable a
  • two elements of the array variable aa

There are no other objects of type A, neither variables nor temporary objects.

Assignment does not create any objects. The line aa[0] = a; does not create any new A object. It just calls the operator= overload of A that you defined.

Since there are three objects of type A, there should be three calls to the destructor of A, one for each object of type A.

CodePudding user response:

Shouldn't the destructor be called 4 times?

No the destructor should not be called 4 times as you're only constructing the object 3 times for which you get the corresponding 3 destructor calls.

It seems that you're expecting a destructor call corresponding to the assignment aa[0] = a;. But assignments does not involve creation of new objects. To be more precise, you're doing copy assignment and not copy initialization.

In particular, your assignment statement as[0] = a; is the same as:

aa[0].operator=(a); //this involves no construction of any new objects

In the above statement, there is no creation of any new objects. So, there are only three A objects for which you get the 3 constructor and 3 destructor calls.

  •  Tags:  
  • c
  • Related