Exception specifications when deriving from std::exception in C++11

空扰寡人 提交于 2019-12-04 02:52:52

Empty throw specifications are useful, as they actually enable compiler optimizations at the caller's site, as Wikipedia knows (I don't have a technical quote handy).

And for reasons of optimization opportunities, nothrow-specifications are not deprecated in the upcoming standard, they just don't look like throw () any more but are called noexcept. Well, yes, and they work slightly differently.

Here's a discussion of noexcept that also details why traditional nothrow-specifications prohobit optimizations at the callee's site.

Generally, you pay for every throw specification you have, at least with a fully compliant compiler, which GCC has, in this respect, appearantly not always been. Those throw specifications have to be checked at run-time, even empty ones. That is because if an exception is raised that does not conform to the throw specification, stack unwinding has to take place within that stack frame (so you need code for that in addition to the conformance check) and then std::unexpected has to be called. On the other hand, you potentially save time/space for every empty throw specification as the compiler may make more assumptions when calling that function. I chicken out by saying only a profiler can give you the definitive answer of whether your particular code suffers from or improves by (empty!) throws specification.

As a workaround to your actual problem, may the following work?

  • Introduce #define NOTHROW throw () and use it for your exception's what and other stuff.
  • When GCC implements noexcept, redefine NOTHROW.

Update

As @James McNellis notes, throw () will be forward-compatible. In that case, I suggest just using throw () where you have to and, apart from that, if in doubt, profile.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!