wulujey
wulujey

Reputation: 414

Destructor in derived class marked as noexcept(false)

There is following code:

class Member
{
public:
  ~Member() noexcept(false) {}
};

class A
{
public:
  virtual ~A() {}
};

class B : public A
{
public:
  Member m;
};

The error is:

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 does the destructor in class B is marked as noexcept(false)? It seems that it somehow gets it from Member class. It was compiled by g++ 6.3.

Upvotes: 5

Views: 322

Answers (1)

François Andrieux
François Andrieux

Reputation: 29022

B's destructor will destroy m, which is not a noexcept operations. You can't be sure that ~B won't throw, so it is also noexcept(false).

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

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

Upvotes: 9

Related Questions