+ 5
c++ vector question
I want to know why the destructor is called 6 times and cnt is 1 Can someone explain this thx #include <iostream> #include <vector> using namespace std; class A{ public: static int cnt; A(int a){} ~A(){ cout << "dtor\n"; ++cnt; } }; int A::cnt = 0; int main() { vector<A> v(5, 2); cout << A::cnt << endl; return 0; }
3 Respostas
+ 3
. � in this case, one constructor is created and it's 5 copies (copy constructor) will be added to vector... the created constructor gets destroyed (cnt set to 1) as soon as your vector initialise line is executed... as of now, you have only five object available in vector due to copy construction...
so, A::cnt prints 1...after that when vector scope is over, at end of main function, destructor gets called for five times... so, total six destructor printing you are getting... if you print cnt value in destructor, you will feel that count is also incremented each time but in your case, you have printed value of count before it got incremented by destroy of copy constructor
+ 3
Ketan Lalcheta thank you
+ 2
. � below code to showcase whatever I said in above comment:
https://code.sololearn.com/ctsodEn2T2x2/?ref=app