什么时候应该显式地赋予noexcept属性? [英] When should one explicitly attribute noexcept?

查看:175
本文介绍了什么时候应该显式地赋予noexcept属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时应该将 noexcept 属性添加到函数中?即编译器什么时候不能告诉函数抛出?


我不喜欢过早的优化,也不喜欢过早的归因。


我不喜欢过早的优化,也不喜欢过早的归因。我不知道如何配置 noexcept 的需求与优化时分析性能的方式相同。


在需要评估的地方,请评论最常见的编译器,例如MSVC,GCC等。

解决方案

C ++核心准则建议基本上在代码不会抛出的任何地方使用它。这对于库来说最重要,因为代码检查器会使用您调用的函数来查看其是否为 noexcept ,否则会收到一连串的警告。


也就是说,最重要的建议是使交换移动和析构函数 noexcept


《 C ++核心准则》还建议使默认构造函数 noexcept 很好,但是许多模式(例如 pImpl习惯用法)通常会在其默认构造函数中分配内存。因此,我通常在默认构造函数(或仅使用默认参数的构造函数)上使用 noexcept ,但是如果我知道它会抛出异常,我会明确指出将其标记为 nothrow(false)


如果声明了默认构造函数,则复制构造函数,赋值运算符,移动构造函数,移动运算符或析构函数为 = default ,它隐式为 noexcept 。所有析构函数也都隐式地 noexcept




您可以将 noexcept 标记为如果确实抛出,请继续崩溃。我发现这个概念有些笨拙,因此在我的代码中我标记了可以抛出 noexcept(false)或未指定它的东西。通常是调用 new 或初始化 std 容器的东西。



When should one add the noexcept attribute to a function? i.e. when is the compiler not able to tell a function throws? Should everything be marked or is there a way to tell?

I'm not a fan of premature optimization, and I'm not a fan of premature attribution. I don't know of a way to "profile" the need of noexcept the same way I profile performance when optimizing.

When evaluating where it is necessary, please comment on the most common compilers, e.g. MSVC, GCC, etc.

解决方案

The C++ Core Guidelines recommends basically use it everywhere that the code doesn't throw. This is mostly important for libraries because code checkers use the functions you call to see if it's noexcept, otherwise you get a cascade of warnings.

That said, the most important recommendations are to make swap, move, and destructors noexcept.

The C++ Core Guidelines also recommends making default constructors noexcept which is great in general, but many patterns (like the pImpl idiom) often allocate memory in their default constructor. Therefore, I generally use noexcept on default constructors (or constructors that only take defaulted parameters), but if I know it can throw I make a point of explicitly marking it nothrow(false).

If you declare a default constructor, copy constructor, assignment operator, move constructor, move operator, or destructor to be =default it's implicitly noexcept. All destructors are also implicitly noexcept.

There's a notion that you can mark something noexcept to mean "if this does throw, go ahead and crash". I find this notion a bit wooly so in my code I mark things that can throw noexcept(false) or leave it unspecified. That's usually stuff that calls new or initializes std containers.

这篇关于什么时候应该显式地赋予noexcept属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆