c++ - 程序在 VS2017 上以 "abort() has been called"错误结束

标签 c++ c++11 visual-studio-2012 visual-studio-2017 c++14

下面的代码通过给出错误退出

"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 发行说明没有提及任何有关异常处理更改的内容。

所以我有以下问题:

  1. 从 VS2017 开始在析构函数中抛出异常是否不正确?它总是通过调用 abort() 退出程序吗?
  2. 是否有任何标志可以使它正常工作?

请推荐。

最佳答案

这里的问题是默认情况下所有的析构函数都是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/

相关文章:

c++ - 将数字分配给 char 类型并进行算术运算?

php - 通过多用户网页重复执行linux程序而不崩溃

c++ - 如何使用 uint64_t 键类型从 std::map<int, std::string> 返回值?

mysql - 在 win 2008r2 上为 PostgreSQL 9.5 编译 mysql_fdw

c++ - UINT64 不是 boost 的成员

c++ - 在 Visual Studio 2005 中创建 DLL

c++ - 当变量打印未初始化的变量包含时,在 C++ 中该怎么办?

c++ - 预期 { 在析构函数之前

c++ - lcov 报告未执行静态成员变量析构函数中的行

c# - 带有 VSIX 安装程序和 Nuget 包的 Visual Studio 2012 的多项目/解决方案模板