gpt4 book ai didi

C++ throw() 优化

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:59:31 24 4
gpt4 key购买 nike

根据 Optimizing C++ ,

Use the empty exception specification (that is, append throw() to the declaration) for the functions you are sure will never throw exceptions.

如果我知道我的 90% 的方法不会抛出异常怎么办?将 throw() 附加到所有这些方法似乎非常规且冗长。如果没有,有什么好处?还是我误解了什么?

最佳答案

C++11 引入了 noexcept , throw有点被弃用(并且根据 this 效率较低)

noexcept is an improved version of throw(), which is deprecated in C++11. Unlike throw(), noexcept will not call std::unexpected and may or may not unwind the stack, which potentially allows the compiler to implement noexcept without the runtime overhead of throw().

当违反空抛出规范时,您的程序将终止;这意味着你应该只将你的函数声明为不抛出,只有当它们有不抛出异常保证时。

最后,您需要一个非抛出的移动构造函数(用 noexcept 指定)才能使用 std::vector<T>::push_back 的右值引用版本(参见更好的解释 here )

关于C++ throw() 优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26789046/

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