代码之家  ›  专栏  ›  技术社区  ›  Ashot

编译器错误:destructor的throw说明符松动

  •  1
  • Ashot  · 技术社区  · 6 年前
    #include <iostream>    
    
    struct ICantChange
    {
        virtual ~ICantChange() {}
    };
    
    struct ClassThatThrows
    {
        virtual ~ClassThatThrows() noexcept(false)
        {
            throw 44;
        }
    };    
    
    struct Test : ICantChange
    {
        ~Test() 
        {
        }    
        ClassThatThrows instance;
    };
    
    main()
    {
        try 
        {
            Test obj;
        }
        catch(int except)
        {
            std::cout << "caught" << std::endl;
        }
    }
    

    此代码给出错误消息:

    main.cpp:20:5: error: looser throw specifier for ‘virtual Test::~Test() noexcept (false)’
         ~Test()
         ^
    main.cpp:6:13: error:   overriding ‘virtual ICantChange::~ICantChange() noexcept’
         virtual ~ICantChange() {}
    

    要修复这个错误,我看到的唯一选择是添加 noexcept(false) 到类的析构函数 ICantChange 我不能,因为这是图书馆的课程。

    我知道扔破坏者是坏的,但现在我有了 Test 类和我希望捕获在它被销毁时引发的异常。

    有人能提出解决方案吗?

    1 回复  |  直到 6 年前
        1
  •  0
  •   Matthieu Brucher    6 年前

    你的问题是那个析构函数 noexcept(true) ,因此通过添加 noexcept(false) 你违背了诺言。

    但不要抛出析构函数: throwing exceptions out of a destructor