+ 9
Why vector constructor call the destructor of class T?
I cannot explain the output when removing the comments to the attached code. Class A has 2 static variables that count of many times a constructor and a destructor is called. Main program create a vector of 10 A object inside a block. As expected the constr and destruc are called 10 time each. However if A constructor needs a param, the output is 1 call the the constru tor and 11 to the destructor...why? https://code.sololearn.com/ckn07geD61K9/?ref=app
4 Answers
+ 9
`vector<A> v(10);` will call the default constructor (the one without parameters) 10 times.
`vector<A> v(10, 1234);` does two things:
- 1234 will be converted to type A implicitly, that's why you see that the constructor was called once. It's as if you wrote
A a(1234);
vector<A> v(10, a);
- the resulting object will be copied 10 times by calling the copy constructor. You can see it by adding a custom copy constructor to your class like
A(A const & a) { cout << "copied" << endl; }
So that's 11 objects total, all of which will be destroyed.
+ 5
Just to visualize what (IMHO perfectly) Schindlabua said.
Hope it will help someone else.
https://code.sololearn.com/c0g6YEpA2bl6/?ref=app
+ 3
perfect Schindlabua
+ 2
Clear. thank you!