问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/27747956/why-is-the-destructor-called-more-than-the-constructor