gpt4 book ai didi

c++ - 什么时候应该明确地赋予 noexcept 属性?

转载 作者:行者123 更新时间:2023-12-01 14:57:03 27 4
gpt4 key购买 nike

什么时候应该添加 noexcept归因于函数?即编译器何时无法判断函数抛出?一切都应该被标记还是有办法告诉?
我不喜欢过早优化,也不喜欢过早归因。我不知道有什么方法可以“描述”noexcept 的需求与我在优化时分析性能的方式相同。
在评估必要的地方时,请评论最常见的编译器,例如MSVC、GCC 等

最佳答案

C++ Core Guidelines建议基本上在代码不会抛出的任何地方使用它。这对于库来说非常重要,因为代码检查器使用您调用的函数来查看它是否是 noexcept ,否则您会收到一连串警告。
也就是说,最重要的建议是制作 swap , move , 和析构函数 noexcept .
C++ 核心指南还建议使用默认构造函数 noexcept这通常很好,但许多模式(如 pImpl idiom )经常在其默认构造函数中分配内存。所以我一般用noexcept在默认构造函数(或仅采用默认参数的构造函数)上,但如果我知道它可以抛出,我会明确标记它 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.

关于c++ - 什么时候应该明确地赋予 noexcept 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63727975/

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