加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 特殊成员函数是noexcept还是throw()?

发布时间:2020-12-16 07:01:48 所属栏目:百科 来源:网络整理
导读:C 11规范很清楚,隐式生成的特殊函数(即默认构造函数,析构函数,复制/移动构造函数和复制/移动赋值运算符)具有异常规范.但规范似乎只是根据现已弃用的动态异常规范(即“throw(T1,T2,T3)”)来编写.这由15.4 / 14中的示例支持: struct A { A(); A(const A) thro
C 11规范很清楚,隐式生成的特殊函数(即默认构造函数,析构函数,复制/移动构造函数和复制/移动赋值运算符)具有异常规范.但规范似乎只是根据现已弃用的动态异常规范(即“throw(T1,T2,T3)”)来编写.这由15.4 / 14中的示例支持:

struct A {
  A();
  A(const A&) throw();
  A(A&&) throw();
  ~A() throw(X);
};
struct B {
  B() throw();
  B(const B&) throw();
  B(B&&) throw(Y);
  ~B() throw(Y);
};
struct D : public A,public B {
  // Implicit declaration of D::D();
  // Implicit declaration of D::D(const D&) throw();
  // Implicit declaration of D::D(D&&) throw(Y);
  // Implicit declaration of D::D() throw(X,Y);
};

我知道,注释不是规范性的,但值得注意的是,D的复制构造函数被声明为throw()而不是noexcept.它有所不同,因为如果违反了throw()而违反了noexcept,则程序的行为会有所不同.

示例上方15.4 / 14中的文本是规范性的,它说:

An implicitly declared special member function (Clause 12)
shall have an exception-specification. If f is an implicitly declared
default constructor,copy constructor,move constructor,destructor,
copy assignment operator,or move assignment operator,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.

鉴于此处仅引用了动态异常规范,我担心隐式生成的特殊成员函数永远不会被声明为noexcept.那是真的吗?

解决方法

我不相信是这样的.实际要求只是“……如果它直接调用的每个函数都不允许例外,则不允许例外.”

如上所述(§15.4/ 12):

An exception-specification is non-throwing if it is of the form throw(),noexcept,or noexcept(constant-expression) where the constant-expression yields true. A function with a non-throwing exception-specification does not allow any exceptions.

非投掷异常规范不允许任何异常并不完全是一个启示,但我认为这说明非抛出异常规范描述中的措辞几乎逐字逐句地反映在隐式声明的特殊成员函数的要求中.因此,在我看来,任何形式的非抛出异常规范(throw()或noexcept或noexcept(<转换为true>的任何东西))都是允许的 – 并且这是特别预期的,而不仅仅是一次事故措辞.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读