-
Hello, this is a small example of a problem with vector I found.The 2. more objects you push inside of the vector, the more constructor and 3. destructor statements you get. I am expecting that there is going to be 4. only one copy when you push an object in the vector, but it looks like 5. there is shift copy happen inside of the vector.
#include <iostream> #include <vector> using namespace std; class What { int i; public: What(int inter) : i(inter) {} What(const What &w) : i(w.i) { static int a = 1; cout << "i am constructor # " << a << "; with value i = " << i << endl; ++a; } ~What() { cout << "i am distractor #" << i << endl; } }; class Whatever { vector<What> w; public: void push(What &what) { w.push_back(what); } }; int main() { What w1{1}; What w2{2}; What w3{3}; Whatever ever; ever.push(w1); ever.push(w2); ever.push(w3); }
the result:
i am constructor # 1; with value i = 1
i am constructor # 2; with value i = 2
i am constructor # 3; with value i = 1
i am distractor #1
i am constructor # 4; with value i = 3
i am constructor # 5; with value i = 1
i am constructor # 6; with value i = 2
i am distractor #1
i am distractor #2
i am distractor #1
i am distractor #2
i am distractor #3
i am distractor #3
i am distractor #2
i am distractor #1
Aucun commentaire:
Enregistrer un commentaire