Marcus Junius Brutus Marcus Junius Brutus - 2 months ago 20
C++ Question

vector constructor / destructor calls

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 was expecting zero constructors and zero destructors to be called for class
A
.

I am using g++ 4.8.4.

Answer

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

Comments