+ 8

challenge explanation

What is the output of this code? #include <iostream> #include <vector> using namespace std; class A { public: static int cnt; A(int a){} ~A(){ ++cnt;} }; int A::cnt = 0; int main() { vector<A> v(4, 1); v.push_back(1); cout << A::cnt << endl; return 0; } from where cnt got 6 ?

7th Oct 2019, 10:31 AM
ABADA S
ABADA S - avatar
1 Resposta
+ 5
there is no better than that but I will write it in my way to ensure that I understood a temporary object is created and assigned to 1 then this object is assigned to more 4 object then it will be destroyed makes cnt 1 after push back another 4 objects created and the old 4 objects destroyed makes cnt 5 another temporary object for (1) which is the new element will be created and destroyed so that cnt 6 vector is like a dynamic array allocated by malloc and any push is like realloc() call isn't it?
7th Oct 2019, 9:09 PM
ABADA S
ABADA S - avatar