Destructor in a derived class marked as noexcept (false)

The following code exists:

class Member { public: ~Member() noexcept(false) {} }; class A { public: virtual ~A() {} }; class B : public A { public: Member m; }; 

Error:

 main.cpp:13:7: error: looser throw specifier for 'virtual B::~B() noexcept (false)' class B : public A ^ main.cpp:10:11: error: overriding 'virtual A::~A() noexcept' virtual ~A() {} ^ 

Why is the destructor in class B marked noexcept (false)? It seems that he is somehow getting it from the Member class. It was compiled by g ++ 6.3.

+5
source share
1 answer

B destructor will destroy m , which is not noexcept operations. You cannot be sure that ~B will not throw, so this is also noexcept(false) .

See http://en.cppreference.com/w/cpp/language/destructor#Implicitly-declared_destructor :

[...] In practice, implicit destructors are no exception if the class is "poisoned" by the base or a member whose destructor is no exception (false).

+9
source

Source: https://habr.com/ru/post/1271365/


All Articles