tags:

views:

339

answers:

5

Apologies if the question sounds silly, I was following experts in SO and trying some examples myself, and this is one of them. I did try the search option but didn't find an answer for this kind.

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

int main()
{
    vector<A> t;
    t.push_back(A()); // After this line, when the scope of the object is lost.
}

Why is the destructor of the class called twice ?

+21  A: 

To add the element a copy constructor is invoked on a temporary object. After the push_back() the temporary object is destroyed - that't the first destructor call. Then vector instance goes out of scope and destroys all the elements stored - that's the second destructor call.

sharptooth
dicaprio
@dicaprio: Sure, until you defined your own copy constructor the compiler used its own automatically generated copy constructor.
sharptooth
+3  A: 

The destructor is called once when the temporary sent to push_back is destroyed and once when the element in t is destroyed.

Andreas Brinck
+9  A: 

This will show you what's happening:

struct A {
  A() { cout << "contruction\n"; }
  A(A const& other) { cout << "copy construction\n"; }
  ~A() { cout << "destruction\n"; }
};

int main() {
  vector<A> t;
  t.push_back(A());
}
Roger Pate
!Roger : I tried the same just before you posted this, I got the point, thank you !!
dicaprio
A: 

Any STL container works with copy of object

den bardadym
A: 

Probably the underlying backing array of the vector gets resized and the elements moved (copied) to the new backing array?

Sergej Koščejev