P3141: std::terminates()
A new WG21 paper is available.
Document number: P3141
Date: 2016-04-01
std::terminates()
by Hal T. Ng, Professor, C.S., LLVM.edu
Excerpt:
In 2014, the C++ committee tackled the problem of C++98’s subtly hard-to-use
std::uncaught_exception()
, which was intended to return whether there were unhandled exceptions but did not work as intended in all destructor cases. The committee successfully addressed the problem by providing the improvedstd::uncaught_exceptions()
(note plural “s”), which returns the number of unhandled exceptions in the current thread, and this function can now be used to reliably implementscope_guard
and similar patterns in portable code.Continuing in the same vein, this paper proposes to address C++98’s related and sometimes-problematic
std::terminate()
. As its name suggests, the function causes abrupt program halts, which can cause data corruption if operations in flight are not completed gracefully. Theset_terminate_handler()
facility only partly addresses this problem by allowing a last-ditch handler to be invoked after unstoppable termination has already begun.Along the same lines as conditional
noexcept
(noexcept(cond)
), we propose a way for a sensitive operation, or a whole program, to determine in advance whether termination is possible. A program can test this by calling:
- namespace std {
- bool terminates();
- }
which returns
true
if and only if the program can subsequently terminate.Because this function cannot fail to determine a valid result, it should be
noexcept
. Further, anticipating its usefulness in constant expressions and following LWG’s guidance for usingconstexpr
wherever possible throughout the standard library, we propose in full:
- namespace std {
- constexpr bool terminates() noexcept;
- }
Implementation notes: This function is so simple to specify that we foresee no implementation difficulty in any of the major C++ compilers.
Note that this is not the same as the halting problem, which would be to return
true
if and only if the program will halt, and which is known to take several hours to compute for programs longer than a few tens of millions of lines. Rather, this function is carefully constructed to returntrue
if and only if the program could terminate, which is fundamentally different and well understood problem.Acknowledgments: This paper expands on the core idea that was first proposed in committee hallway discussion by P.J. Plauger.