Why is a destructor called more than a constructor?

In the following code, the destructor is called twice, and the constructor is called only once:

enum TFoo { VAL1, VAL2 }; class CFoo { public: TFoo mf; CFoo() { cout<<"hi c'tor1\n"; //mf = f; } CFoo(TFoo f) { cout<<"hi c'tor2\n"; mf = f; } CFoo(TFoo &f) { cout<<"hi c'tor3\n"; mf = f; } ~CFoo() { cout<<"bye\n"; } }; int main() { vector<CFoo> v; //v.assign(1, VAL1); v.push_back(VAL1); } 

Code Outputs:

 hi c'tor2 bye bye 

I found a similar question that mentioned copy constructors, so I added them, but with the same result. Uncommenting the line //v.assign(1, VAL1); also does not change anything.

+7
c ++ destructor
source share
1 answer

It is first created using the implicit conversion operator between TFoo and CFoo , CFoo(TFoo f) , and then uses this temporary object to pass it to push_back to create an object in the container using the default copy constructor or move the constructor, depending on Are you using C ++ 11 (which doesn't display anything). Then the temporary is destroyed and, finally, the object in the container (with the container itself).

You can see here or here (C ++ 11) even better.

+9
source share

All Articles