gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:04 25 4
gpt4 key购买 nike

下面的代码是合法的吗?

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

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

(throw() 已弃用,但我的编译器不支持 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.

因此,如果它与析构函数的隐式声明所具有的异常规范完全匹配,那么您只能给出一个显式的异常规范。

隐式析构函数的异常规范取决于它调用的函数:

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.

析构函数调用的函数是类的非静态数据成员、基类和虚拟基类的析构函数。

在您的情况下,由于该类没有数据成员和基类,因此它不调用任何函数,因此它属于最后一种情况。它直接调用的每个函数(没有)不允许有异常,所以这个析构函数必须不允许有异常。因此,您的异常规范必须是非抛出的,因此 nothrowexcept()exception(产生 true 的常量表达式)是您可以提供的唯一合适的异常规范,因此您的代码没有问题。

关于C++ : noexcept (or throw()) virtual destructor = default;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21214653/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com