为什么类的析构器调用了两次? [英] Why is the destructor of the class called twice?

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

问题描述

如果问题听起来很愚蠢,我表示歉意,我是在跟随SO的专家,自己尝试一些例子,这是其中之一。我没有尝试搜索选项,但没有找到这样的答案。

Apologies if the question sounds silly, I was following experts in SO and trying some examples myself, and this is one of them. I did try the search option but didn't find an answer for this kind.

class A
{
    public:
         A(){cout<<"A Contruction"<<endl;}
        ~A(){cout<<"A destruction"<<endl;}
};

int main()
{
    vector<A> t;
    t.push_back(A()); // After this line, when the scope of the object is lost.
}

为什么类的析构函数调用两次?

Why is the destructor of the class called twice ?

推荐答案

要添加元素,在临时对象上调用复制构造函数。在 push_back()后,临时对象被销毁 - 这是第一个析构函数调用。然后向量实例超出范围并销毁所有存储的元素 - 这是第二个析构函数调用。

To add the element a copy constructor is invoked on a temporary object. After the push_back() the temporary object is destroyed - that't the first destructor call. Then vector instance goes out of scope and destroys all the elements stored - that's the second destructor call.

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

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