+ 1

A question

Why the answer is 6 not 5? I won't write necessary headers, please don't say it will give an error. class A{ public: static int cnt; A(int a){} ~A(){++cnt;} }; int main(){ vector<A> v(4,1); v.push_back(1); cout<<A::cnt<<endl; }

17th Jun 2018, 7:11 PM
Yusuf
Yusuf - avatar
2 Answers
+ 1
i think its the following reason, but i‘m not 100% sure. vector<A> v(4,1) creates 4 objects so 4 constructor calls and v.push_back(1) creates a temporary object from 1 by calling the constructor, it gets passed by value to push_back, now the temporary object is no longer needed and gets deleted so 1 deconstructor call. so overall 5 constructor calls and 1 deconstructor call by the way i think your constructor is incomplete
17th Jun 2018, 9:36 PM
Max
Max - avatar
+ 1
It seems so complex, because I couldn't understand how this vector class works. Thank you.
17th Jun 2018, 9:39 PM
Yusuf
Yusuf - avatar