为什么析构函数在抛出异常时调用了两次?

Alo*_*lok 1 c++

我很困惑为什么在抛出excpetion时会调用两次destrctor,以及它们被称为??

#include <iostream> 
using namespace std;
class base
{
 public:
     base(){cout<<"constructor called"<<endl;}
     ~base(){cout<<"destructor called"<<endl;}
};
void fun()
{
     throw base(); //<=- Create temp obj of base, and throw exception

}
int main()
{
    try
    {
        fun();
    }
    catch(...)
    {
        cout<<"handle all exception"<<endl;
    }

}
Run Code Online (Sandbox Code Playgroud)

以下是输出

constructor called
destrctor called
handle all exception
destuctor is called
Run Code Online (Sandbox Code Playgroud)

但是当我添加了复制构造函数时,它从未调用过但是析构函数只调用一次,所以发生了什么?

#include <iostream> 
using namespace std;
class base
{
 public:
     base(){cout<<"constructor called"<<endl;}
     ~base(){cout<<"destructor called"<<endl;}
     base (base &obj){cout<<"copy constructor called"<<endl;}
};
void fun()
{
     throw base(); //<=- Create temp obj of base, and throw exception
}
int main()
{
    try
    {
        fun();
    }
    catch(...)
    {
        cout<<"handle all exception"<<endl;
    }

}
Run Code Online (Sandbox Code Playgroud)

输出:

constructor called
handle all exception
destrctor called
Run Code Online (Sandbox Code Playgroud)

Joh*_*ohn 7

因为异常对象是在catch中复制的.用于catch (base&v)通过引用获取,而不是值.


Pup*_*ppy 7

编译器可以根据需要多次复制您的异常对象.析构函数被调用两次,因为它有一个副本.