+ 4

11 destructor and 2 constructor for 5 objects???

#include <iostream> #include <vector> using namespace std; class A { public: static int cnt; int a; A(int a) { A::a = a; cout << "I am a " << cnt << " constructor!" << endl; } ~A() { ++cnt; cout << "I am a " << cnt << " destructor!" << endl; } }; int A::cnt = 0; int main() { vector<A> v(4, 1); v.push_back(1); cout << A::cnt << endl; return 0; } This code ouputs: I am a 0 constructor! I am a 1 destructor! I am a 1 constructor! I am a 2 destructor! I am a 3 destructor! I am a 4 destructor! I am a 5 destructor! I am a 6 destructor! 6 I am a 7 destructor! I am a 8 destructor! I am a 9 destructor! I am a 10 destructor! I am a 11 destructor! Why do we have so many destructors and only 2 constructors??

21st Jan 2018, 3:33 PM
Petros Simidyan
Petros Simidyan - avatar
4 Réponses
+ 2
I didn't, it is from chellenge
22nd Jan 2018, 9:10 PM
Petros Simidyan
Petros Simidyan - avatar
+ 2
thanks a lot, that should be usefull
24th Jan 2018, 2:19 PM
Petros Simidyan
Petros Simidyan - avatar
0
one thing I know is when you use combine vector assignment then compiler will create one object temperary and use copy constructor to construct object you have specified. Run below code to verify. #include <iostream> #include <vector> using namespace std; class A { public: static int cnt; int a; A(int a) { this->a = a; cnt++; cout << "I am a " << cnt << " constructor!" << endl; } ~A() { ++cnt; cout << "I am a " << cnt << " destructor!" << endl; } }; int A::cnt = 0; int main() { vector<A> v(1, 1); cout << v.size()<< endl; return 0; }
22nd Jan 2018, 4:31 PM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
- 1
hey, first of all you should keep in mind that for optimization purpose compiler create one object and use copy of that to construct others. vector capacity is responsible for multiple destructor and constructor. Here I added some code to understand what is happening. if count the constructor in output then it is 11. https://code.sololearn.com/cht4WW98g0ot/?ref=app
24th Jan 2018, 1:45 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar