为什么析构函数比构造函数调用得更多? [英] Why is the destructor called more than the constructor?

查看:81
本文介绍了为什么析构函数比构造函数调用得更多?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在以下代码中,析构函数被调用两次,而构造函数仅被调用一次:

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);
}

代码输出:

hi c'tor2
bye
bye

我发现了一个类似的问题,其中提到了复制构造函数,所以我添加了它们,但是具有相同的结果.取消注释行//v.assign(1,VAL1); 也不会更改任何内容.

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.

推荐答案

最初使用 TFoo CFoo CFoo(TFoo f),然后使用该临时对象将其传递给 push_back ,以使用默认的复制构造函数或move构造函数在容器中构造该对象,具体取决于您使用的是C ++11(不显示任何内容).然后临时对象被销毁,最后是容器中的对象(包括容器本身).

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.

这篇关于为什么析构函数比构造函数调用得更多?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆