#include #include #include #include using namespace Void::ScopeGuard; // ── scope_exit ──────────────────────────────────────────────────────────────── Void::Testing::Test scope_exit_fires_on_normal_exit() { int called = 0; { auto g = scope_exit([&] { ++called; }); } Void::Testing::expect_eq(called, 1); } Void::Testing::Test scope_exit_fires_on_exception() { int called = 0; try { auto g = scope_exit([&] { ++called; }); throw std::runtime_error{"oops"}; } catch (...) {} Void::Testing::expect_eq(called, 1); } Void::Testing::Test scope_exit_dismiss_prevents_call() { int called = 0; { auto g = scope_exit([&] { ++called; }); g.dismiss(); } Void::Testing::expect_eq(called, 0); } Void::Testing::Test scope_exit_active_reflects_state() { auto g = scope_exit([] {}); Void::Testing::expect(g.active()); g.dismiss(); Void::Testing::expect(!g.active()); } Void::Testing::Test scope_exit_move_transfers_ownership() { int called = 0; { auto g1 = scope_exit([&] { ++called; }); auto g2 = std::move(g1); Void::Testing::expect(!g1.active()); Void::Testing::expect(g2.active()); } Void::Testing::expect_eq(called, 1); } Void::Testing::Test scope_exit_multiple_guards() { int order = 0, a = 0, b = 0; { auto ga = scope_exit([&] { a = ++order; }); auto gb = scope_exit([&] { b = ++order; }); } // gb fires before ga (LIFO destruction) Void::Testing::expect(b < a); } // ── scope_success ───────────────────────────────────────────────────────────── Void::Testing::Test scope_success_fires_on_normal_exit() { int called = 0; { auto g = scope_success([&] { ++called; }); } Void::Testing::expect_eq(called, 1); } Void::Testing::Test scope_success_does_not_fire_on_exception() { int called = 0; try { auto g = scope_success([&] { ++called; }); throw std::runtime_error{"oops"}; } catch (...) {} Void::Testing::expect_eq(called, 0); } // ── scope_failure ───────────────────────────────────────────────────────────── Void::Testing::Test scope_failure_does_not_fire_on_normal_exit() { int called = 0; { auto g = scope_failure([&] { ++called; }); } Void::Testing::expect_eq(called, 0); } Void::Testing::Test scope_failure_fires_on_exception() { int called = 0; try { auto g = scope_failure([&] { ++called; }); throw std::runtime_error{"oops"}; } catch (...) {} Void::Testing::expect_eq(called, 1); } // ── practical usage ─────────────────────────────────────────────────────────── Void::Testing::Test scope_exit_resource_cleanup() { bool released = false; auto acquire = [&]() -> int { return 42; }; { int handle = acquire(); auto cleanup = scope_exit([&] { if (handle) released = true; }); (void)handle; } Void::Testing::expect(released); } Void::Testing::Test scope_exit_conditional_commit() { int value = 0; bool committed = false; { value = 10; auto rollback = scope_exit([&] { value = 0; }); // Simulate successful operation — commit. committed = true; if (committed) rollback.dismiss(); } Void::Testing::expect_eq(value, 10); }