mardi 23 octobre 2018

Compiler error: looser throw specifier for destuctor

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

This code gives error message:

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() {}

To fix that error the only option I see is to add noexcept(false) to the destructor of class ICantChange that I cant because it is a library class.

I know that throwing destructors are bad but now I have Test class and I want to catch exceptions that are thrown when it is destructed.

Can anyone suggest a solution?

Aucun commentaire:

Enregistrer un commentaire