1

I have the following code:

#include <iostream>
#include <vector>

using std::cout;
using std::endl;
using std::vector;

class A {
public:
  int i;
  A(int i=0):i(i) {
    cout << "A::A() called" << endl;
  }
  ~A() {
    cout << "A::~A() called" << endl;
  }

};

int main() {
  vector<A> *a = new vector<A>(3);
  delete a;
}

The program prints:

A::A() called
A::~A() called
A::~A() called
A::~A() called
A::~A() called

Why do I see one constructor and four destructors called ?

I am using g++ 4.8.4.

Marcus Junius Brutus
  • 26,087
  • 41
  • 189
  • 331

1 Answers1

1

When you construct vector of three instances of A, it is filled with default value. Default value is taken from vector constructor argument. You didn't provide one, so it is constructed either by constructor without arguments or by constructor with default argument values. You provided the latter, so the first constructor call.

All three elements are copy-constructed, so no call to your constructor.

Then the default value instance is destroyed, so the first destructor.

Then you delete the vector, which deletes all three instances, calling destructor three times.

Try printing value of this in the functions to try for yourself or try this sample: http://coliru.stacked-crooked.com/a/903fa70484f5c3bc

Adam Trhon
  • 2,915
  • 1
  • 20
  • 51
  • 1
    Adding `A(const A& o) { cout << "copy-constructor on" << this << endl; }` confirms this answer. – Marcus Junius Brutus Sep 18 '16 at 21:07
  • Note: C++11 outlawed the practice of copy-constructing vector entries as seen in OP code, now it is required that each entry be default-constructed when the caller didn't supply initializers. – M.M Sep 18 '16 at 21:17