+ 1

Please help with this c++ vector<T>-question :-)

Hey fellow learners, a few hours ago I stumbled upon this question in a c++ challenge and I just can figure out why the answer is what it is. Maybe one of you c++-wizards would care to enlighten me ;-) //assume necessary includes class A { public: static int cnt; A(int a){} ~A() { ++cnt; } }; int A::cnt = 0; int main() { vector<A> v(5,1); cout << A::cnt << endl; // output is 1 return 0; } As I understand the vector v is created with 5 fields for A-objects, that are each instantiated with the value 1. As the static cnt is only incremented on object-destruction, I can't understand why it's output is 1 on the second line of main(). Can anyone please explain why? Thx so much. - code artist

2nd Jan 2019, 9:20 PM
Code Artist
Code Artist - avatar
2 ответов
+ 3
It is just my guess, but I think that this is how it works in this constructor: vector(size, value) { T tmp(value); for(int i = 0; i < size; ++i) { this->push_back(tmp); } } As you can see we create one temporary object which we copy 5 times to our vector. Then this temporary object is destroyed incrementing our static value. It's just a wild guess, it could be a lot simplier solution there, but I cannot really think of one other than that.
2nd Jan 2019, 9:45 PM
Jakub Stasiak
Jakub Stasiak - avatar
+ 2
Thanks Jakub, I think you're right. After a little bit more digging I found a decent decription of the vector-constructor used in the example. Turns out it's exactly as you guessed. The 2nd param is used to create a temp-object that is then copied to all the fields in the vector and destroyed afterwards, hence the dtor-call :-)
2nd Jan 2019, 11:26 PM
Code Artist
Code Artist - avatar