DFord
DFord

Reputation: 2358

Destructor called for each object in an array

I have an array of objects:

Square sq[81];

I think it uses the default constructor to created each.

When I go though a for loop to initialize each, it calls the destructor for each Square object in the array.

for (int k=0; k<9; k++) {
   for(int j=0; j<9; j++) {
      sq[count++] = Square(k, j);
   }
}

When Square(k, j) is called, is it deleting the object in sq[] and creating a new one?

Upvotes: 1

Views: 2578

Answers (3)

Bill
Bill

Reputation: 14685

Let's take the following sample program: http://codepad.org/S1iH4cWD

You can see several important steps:

  • Before main, every object in Square sq[81] is default constructed.
  • In your loops, a temporary is constructed, its contents are assigned to an object in sq - which overwrites what was there - and then the temporary is destructed.
  • Finally, after main, every object in Square sq[81] is destructed, in reverse order of construction.

So you had it almost right, except objects in sq will only be deleted after main ends. It is the temporary (the object on the right side of the =) that is destructed.

You may find this program helpful: http://codepad.org/JPE8uYVO It tracks different values for initialization versus assignment.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

sq[count++] = Square(k, j);

When Square(k, j) is called, is it deleting the object in sq[] and creating a new one?

No.

Square(k, j) creates a new temporary object and = copies it into the old one. The temporary object is then destroyed as it is not longer required and goes out of scope.


BTW, you're not actually initialising anything in the loop (other than that temporary, I mean); you're just assigning, after-the-fact.

Upvotes: 9

Kerrek SB
Kerrek SB

Reputation: 477020

The elements of sq[] aren't getting destroyed. Rather, you call the assignment operator of each element to assign it the new value Square(k, j), and the temporary object gets destroyed at the end of the assignment.

If you want to avoid the redundant default construction plus assignment, you could/should use a vector:

std::vector<Square> sq;
sq.reserve(81);
for (...) for (...) sq.push_back(Square(k,j));

If you further want to avoid the redundant temporary, use C++11 and say,

for (...) for (...) sq.emplace_back(k, j);

Upvotes: 3

Related Questions