nov*_*ice 1 c++ c++11 visual-studio-2012 c++14 visual-studio-2017
下面的代码通过给出错误退出
"abort()被称为".
是因为析构函数抛出异常?我知道从析构函数中抛出异常会导致未定义的行为,但也存在反向参数.此外,相同的程序在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;
}
Run Code Online (Sandbox Code Playgroud)
VS2017发行说明没有提及任何有关异常处理更改的内容.
所以我有以下问题:
请建议.
这里的问题是默认的所有析构函数都是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;
}
Run Code Online (Sandbox Code Playgroud)
该程序按预期运行.
这在VS2012中有效但不是VS2017的原因是在C++ 11之前,析构函数可以抛出而不需要指定它.使用C++ 11 noexcept说明符以及noexcept默认情况下所有析构函数的更改会导致它在VS2017中断.