Why is the destructor called more than the constructor? [duplicate]

谁说我不能喝 提交于 2021-02-04 17:29:27

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!