+ 3
Vector and static variable
Hi! #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> a(5,1); cout << A::cnt; } Output: 1 I do not understand, where I set A::cnt = 1 I have in destructor cnt++, but not call that during executing
2 Réponses
+ 7
Interesting. Take a look at this fork of your code:
https://code.sololearn.com/cmQjiTMGH600/?ref=app
What you see, is the constructor and destructor each executing three times before the print statement in main. After the print statement, the destructor executes another 3 times.
The program most probably created three temporary objects of class A, which is destroyed after being assigned to the vector object. Upon program termination, the objects of class A which is stored in the vector object is then destroyed along with the destruction of the vector object, which causes the destructor of class A to be called another 3 times.
Note that whatever value you "assign" to the objects of class A, will not be stored within A::cnt. Your constructor does not assign its argument to cnt. Hence, whatever your input is, cnt will begin with 0. Since cnt is static, all increment operation is done on the same member, A::cnt.
0
So, vector during initialze copies A to other memory without inirialize and destroy original A. Interesting