Why will std::uncaught_exception change to std::uncaught_exceptions?

前端 未结 3 2004
伪装坚强ぢ
伪装坚强ぢ 2020-12-15 07:49

I just noticed over on

http://en.cppreference.com/w/cpp/error/uncaught_exception

that C++17 will replace std::uncaught_exception(), which return

相关标签:
3条回答
  • 2020-12-15 08:17

    The paper that introduced this was n4152, which has the rationale (which generally boils down to "make ScopeGuard work")

    To quote,

    as documented at least since 1998 in Guru of the Week #47, it means code that is transitively called from a destructor that could itself be invoked during stack unwinding cannot correctly detect whether it itself is actually being called as part of unwinding. Once you’re in unwinding of any exception, to uncaught_exception everything looks like unwinding, even if there is more than one active exception.

    And

    this uses information already present in major implementations, where current implementations of ScopeGuard resort to nonportable code that relies on undocumented compiler features to make ScopeGuard “portable in practice” today. This option proposes adding a single new function to expose the information that already present in compilers, so that these uses can be truly portable

    PS: Here's an example of how this function can be implemented using compiler-speicific information: https://github.com/panaseleus/stack_unwinding/blob/master/boost/exception/uncaught_exception_count.hpp

    And for a simple example where it's used, look no further than boost.log's "record pump" (see boost/log/detail/format.hpp and boost/log/sources/record_ostream.hpp): it makes it possible for BOOST_LOG(lg) << foo(); to log in the destructor of the guard object it creates if foo doesn't throw, that is, if the number of exceptions in flight when the destructor is called is not greater than when the constructor was called.

    0 讨论(0)
  • 2020-12-15 08:25

    std::uncaught_exception() only detects whether the stack is unwinding. In a paper by Herb Sutter, he points out that this does not reliably indicate that there is an active exception. Herb opines that this is "almost" useful. I have encountered a situation where this is indeed ambiguous, which is what led me to this post.

    std::uncaught_exceptions() is specified as returning the number of active exceptions, which is actually useful.

    0 讨论(0)
  • 2020-12-15 08:26

    note that std::uncaught_exception() can still be useful for debug/loginfo. It can help determine where the exception originated. However I agree functionally, its quite useless.

    0 讨论(0)
提交回复
热议问题