Did I understand correctly this C++ challenge code? | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

Did I understand correctly this C++ challenge code?

https://code.sololearn.com/cJVJFCDBroOd/?ref=app I had a hard time understanding what is going on here, but I think I have an explanation now, and i would like a confirmation that I'm reasoning correctly. vector<A> v(4,1); This uses a temporary A object for all 4 initial elements, hence the destructor is called only for that temporary. ==> 1 destructor called ==> cnt == 1 v.push_back(1); The vector needs to be resized in order to accommodate for the new element which will be inserted, so the destructor of the 4 A objects is called, as they get copied into the resized vector. Then the new element is inserted using a temporary A, whose destructor is then called. ==> 4 destructor calls for the 4 A in the vector + 1 destructor call for the temporary ==> 6 total calls Did I get it right?

8th Oct 2018, 7:55 AM
fra
fra - avatar
1 ответ
0
Disclaimer: I am not an expert, but heres what i think. I agree for the some part because i have the same understanding, except, "destructor of the 4 A objects is called as they get copied to the resized vector" Im pretty sure that the 4 A destructor only called when the first push_back, because if the destructor called every 'copy' like what you said, then if you push back more elements, the cnt should be increased by the number of the elements, because they get 'copied'
8th Oct 2018, 3:19 PM
Owenizedd
Owenizedd - avatar