Skip to content

Commit 2672397

Browse files
scope_fail
1 parent 6d77a7a commit 2672397

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

include/beman/scope/scope.hpp

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -444,6 +444,27 @@ class ReleasableExecuteWhenNoException
444444
};
445445

446446

447+
//======
448+
449+
class ReleasableExecuteOnlyWhenException
450+
{
451+
public:
452+
[[nodiscard]] bool operator()() const noexcept(noexcept(std::uncaught_exceptions()))
453+
{
454+
return m_uncaught_on_creation < std::uncaught_exceptions();
455+
}
456+
457+
458+
void release()
459+
{
460+
m_uncaught_on_creation = INT_MAX;
461+
}
462+
463+
private:
464+
int m_uncaught_on_creation = std::uncaught_exceptions();
465+
};
466+
467+
447468
//==================================================================================================
448469

449470
// --- type aliases ---
@@ -457,6 +478,9 @@ using scope_success = scope_guard<ExitFunc,
457478
ReleasableExecuteWhenNoException,
458479
exception_during_constuction_behaviour::dont_invoke_exit_func>;
459480

481+
template<class ExitFunc>
482+
using scope_fail =
483+
scope_guard<ExitFunc, ReleasableExecuteOnlyWhenException, exception_during_constuction_behaviour::invoke_exit_func>;
460484

461485
} // namespace beman::scope
462486

tests/scope_fail.test.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
#define CATCH_CONFIG_MAIN
1010
#include <catch2/catch_all.hpp>
1111

12-
using namespace beman::scope;
12+
using beman::scope::scope_fail;
13+
using beman::scope::scope_success;
1314

1415
TEST_CASE("scope_fail runs handler on exception", "[scope_fail]") {
1516
bool triggered = false;
@@ -187,11 +188,11 @@ TEST_CASE("scope_fail coexists with scope_success", "[scope_fail][advanced]") {
187188
std::string output;
188189

189190
try {
190-
std::experimental::scope_success success([&]() {
191+
scope_success success([&]() {
191192
output += "success ";
192193
});
193194

194-
std::experimental::scope_fail fail([&]() {
195+
scope_fail fail([&]() {
195196
output += "fail ";
196197
});
197198

0 commit comments

Comments
 (0)