简体   繁体   中英

C++ : noexcept (or throw()) virtual destructor = default;

The following code is legal?

class C
{
    virtual ~C() noexcept = default;
};

or

class C
{
    virtual ~C() throw() = default;
};

(throw() is deprecated, but my compiler doesn't support noexcept ;;)

8.4.2 [dcl.fct.def.default] An explicitly-defaulted function [...] may have an explicit exception-specification only if it is compatible (15.4) with the exception-specification on the implicit declaration.

15.4/3 [except.spec] Two exception-specifications are compatible if:

  • both are non-throwing (see below), regardless of their form,
  • both have the form noexcept(constant-expression) and the constant-expressions are equivalent, or
  • both are dynamic-exception-specifications that have the same set of adjusted types.

So you can only give an explicit exception-specification if it exactly matches the one that the implicit declaration of the destructor would have.

The exception-specification that the implicit destructor would have depends on the functions it would call:

15.4/14 [except.spec] An implicitly declared special member function shall have an exception-specification. If f is an implicitly declared [...] destructor, [...] its implicit exception-specification specifies the type-id T if and only if T is allowed by the exception-specification of a function directly invoked by f's implicit definition; f shall allow all exceptions if any function it directly invokes allows all exceptions, and f shall allow no exceptions if every function it directly invokes allows no exceptions.

The functions that a destructor calls are the destructors of the class's non-static data members, its base classes, and its virtual base classes.

In your case, since the class has no data members and no base classes and therefore it calls no functions, it falls into the final case. Every function it directly invokes (there are none) allows no exceptions, so this destructor must allow no exceptions. Therefore, your exception-specification has to be non-throwing, so nothrow , except() , and exception(constant expression that yields true) are the only appropriate exception-specifications you can give, so your code is fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM