下面的代码通过给出错误退出
"abort() has been called".
是不是析构函数抛异常?我知道从析构函数中抛出异常会导致未定义的行为,但也有反参数。此外,同一程序在 VS 2012 中也能正常工作。
#include "stdafx.h"
#include<iostream>
using namespace std;
class Txn
{
public:
Txn()
{
cout<< "in Constructor" << endl;
};
~Txn()
{
try
{
cout << "in destructor" << endl;
throw 10;
}
catch(int i)
{
cout << "in destructor exception" << endl;
throw;
}
}
};
int main()
{
try
{
Txn t;
}
catch (int i)
{
cout << "Exception" << i << endl;
}
return 0;
}
VS2017 发行说明没有提及任何有关异常处理更改的内容。
所以我有以下问题:
- 从 VS2017 开始在析构函数中抛出异常是否不正确?它总是通过调用 abort() 退出程序吗?
- 是否有任何标志可以使它正常工作?
请推荐。
最佳答案
这里的问题是默认情况下所有的析构函数都是noexcept(true)
。在不更改的情况下抛出异常将立即调用 std::terminate
。如果我们使用
class Txn
{
public:
Txn()
{
cout<< "in Constructor" << endl;
};
~Txn() noexcept(false)
{
try
{
cout << "in destructor" << endl;
throw 10;
}
catch(int i)
{
cout << "in destructor exception" << endl;
throw;
}
}
};
int main()
{
try
{
Txn t;
}
catch (int i)
{
cout << "Exception" << i << endl;
}
return 0;
}
程序按预期运行。
这在 VS2012 中起作用但在 VS2017 中不起作用的原因是在 C++11 之前析构函数可以抛出而无需您指定它。使用 C++11 noexcept
说明符和所有析构函数默认为 noexcept
的更改导致它在 VS2017 中中断。
关于c++ - 程序在 VS2017 上以 "abort() has been called"错误结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740620/