Below is the signature of vector pushback method in C++.
void push_back (const value_type& val);
Now below is code
class MyInt
{
int *a;
public:
MyInt(int n):a(new int(n)){cout<<"constructor called"<<endl;}
~MyInt(){cout<<"destructor called"<<endl;}
void show(){
cout<<*a<<endl;
}
};
void vector_test(vector<MyInt> &v)
{
MyInt m1(1);
MyInt m2(2);
v.push_back(m1);
v.push_back(m2);
}
Output
-------------
constructor called
constructor called
destructor called
destructor called
destructor called
1
2
destructor called
destructor called
Here we see that for 2 objects which is created in vector_test function causes 2 times constructor invocation. But for destructor it got invoked 5 times.
Now my doubts and questions are
- How come number of constructor and destructor calls are not matching?
- I understand that there are some temporary objects getting created. But how this mechanism is working?
- Just to test, I tried to provide a copy constructor but it causes compilation failure. What could be the reason?
- Is there some logic inside which is copying the contents of m1 and m2 into new objects and puts in to the container?
I would really appreciate if someone explain this in detail. Thanks..