In the following code, the destructor is called twice, while 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);
}
The code outputs:
hi c'tor2 bye bye
I found a similar question, which mentioned copy constructors, so I added them, but with the same result. Uncommenting the line //v.assign(1, VAL1);
also doesn't change anything.
It is initially constructing using the implicit conversion operator between TFoo
and CFoo
, CFoo(TFoo f)
, and then using that temporary object to pass it to push_back
to construct the object in the container using the default copy constructor or move constructor, depending on whether you are using C++11 (which is not displaying anything). Then the temporary is destroyed and finally the object in the container (with the container itself).
You can see it here or here (C++11) even better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With