c++ - 为什么抛出异常时析构函数调用两次?

标签 c++

我很困惑为什么在抛出异常时会调用两次析构函数,调用的是哪一点??

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

}

输出如下

constructor called
destrctor called
handle all exception
destuctor is called

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

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

}

输出:

constructor called
handle all exception
destrctor called

最佳答案

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

关于c++ - 为什么抛出异常时析构函数调用两次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6456587/

相关文章:

c++ - 没看懂Stroustup先生建议删除抽象类Shape的copy default和move操作

c++ - 为什么LLVM选择开放寻址哈希表来实现llvm::StringMap?

android - ASSIMP - 安卓 NDK 工具链

c++ - 如何知道磁盘是基本磁盘还是动态磁盘?

c++ - 如何为采用一个参数的类初始化 shared_ptr vector ?

c++ - 在 C++ 中访问通用结构的成员会出错

C++ 无序对类型

c++ - TCP - 如何关闭在线程内创建的客户端 -C++

c++ - 为什么 std::vector 的字符串文字初始值设定项列表不能在 C++ 中创建 std::vector<std::string> ?

c++ - vector 迭代器在赋值重载中不兼容