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

dic*_*rio 24 c++ destructor

抱歉,如果这个问题听起来很愚蠢,我就是在关注SO的专家并亲自尝试一些例子,这就是其中之一.我确实尝试了搜索选项,但没有找到这种答案.

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.
}
Run Code Online (Sandbox Code Playgroud)

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

sha*_*oth 45

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

  • @dicaprio:当然,在您定义自己的复制构造函数之前,编译器使用自己自己生成的复制构造函数. (4认同)

小智 26

这将告诉你发生了什么:

struct A {
  A() { cout << "contruction\n"; }
  A(A const& other) { cout << "copy construction\n"; }
  ~A() { cout << "destruction\n"; }
};

int main() {
  vector<A> t;
  t.push_back(A());
}
Run Code Online (Sandbox Code Playgroud)