2
#include <iostream>
#include <vector>

using namespace std;

class A
{
    public:
         A(){cout<<"A Contruction"<<endl;}
        ~A(){cout<<"A destruction"<<endl;}
};

int main()
{
    vector<A> t;
    A a;
    A b;
    t.push_back(a);
    t.push_back(b);
    return 0;
}

Output:

A Contruction
A Contruction
A destruction
A destruction
A destruction
A destruction
A destruction

Am unable to understand the destruction call. First 2 destruction are for copy constructor being called in vector.

user6882413
  • 331
  • 2
  • 9

1 Answers1

5

The other three destructions are from objects that get copy and/or move-constructed.

The two calls to push_back will effectively copy-construct a copy of the parameter object in the container itself.

The 2nd call to push_back appears to reallocate the vector, and the sole object in the vector, thus copy-constructing it as well, and then destroying the original object.

Add a copy-constructor to your class, to log the invocations of the copy constructor.

P.S. Actually, if you were to dig into this, it's the 2nd and the third "A destruction" message that log the destruction of your a and b objects. The first "A destruction" message is due to the vector reallocation.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148