martinmoene / scope-lite

A migration path to C++ library extensions scope_exit, scope_fail, scope_success, unique_resource
Boost Software License 1.0
40 stars 6 forks source link

constexpr scope guards #5

Open Morwenn opened 2 years ago

Morwenn commented 2 years ago

Hi, it occurred to me recently that it is easily possible to make scope guards constexpr in C++20 by making uncaught_exceptions constexpr itself. The following function should be very simple yet sufficient:

constexpr int uncaught_exceptions() noexcept
{
    if (std::is_constant_evaluated()) {
        return 0;
    } else {
        return std::uncaught_exceptions();
    }
}

At constexpr time, there shouldn't be any exception in flight at any moment since throw terminates the compilation, therefore we can safely return 0, it will always be true.

I know that basing scope guards on uncaught_exceptions() is fragile because of known issues with coroutines, but the proposed change is arguably rather useful, is a strict improvement to the existing implementation, and makes it work at compile-time, a context where it will correctly work even in the presence of coroutines.

Anyway, thanks for the library :)

martinmoene commented 2 years ago

Thanks @Morwenn, for your interesting observation. I'll try and incorporate it.

martinmoene commented 2 years ago

Todo: