Developer knowledge network · moderated exchange

UnreliableCode қауымдастығы

Әзірлеушілерді зерттеу, кері инженерия және кодтау қауымдастығы

Knowledge indexТірі
4Categories
919Threads
2.8KЖазбалар
Guide

Understanding RAII and Scoped Exit Guards with std::scope_exit and std::scope_fail in C++23 [StackOverflow Architecture Guide]

raii_clean_coder
Modern C++ Advocate
MEMBER
Өкіл: 190
Қосылу күні: Aug 2020
Хабарламалар: 20
Рахмет: 22
4 апта бұрын · Jul 26, 2026 3:07 PM
#1

Writing clean cleanup logic in C++ without complex try/catch blocks using <scope>:

CPP
#include <scope>

void DatabaseTransaction() {
    BeginTransaction();
    // Automatically rolls back if an exception is thrown!
    std::scope_fail rollback([]{ RollbackTransaction(); });
    
    // Automatically releases lock on scope exit (success or failure)
    std::scope_exit cleanup([]{ ReleaseLocks(); });
    
    ExecuteQueries();
    CommitTransaction();
}

std::scope_exit executes upon normal or exceptional scope exit. std::scope_fail executes only if an unhandled exception is currently unwinding the stack!

sanitizer_sam
UB Hunter
MEMBER
Өкіл: 119
Қосылу күні: Apr 2021
Хабарламалар: 10
Рахмет: 53
4 апта бұрын · Jul 26, 2026 7:02 PM
#2

std::scope_fail is the cleanest way to handle transaction rollbacks without polluting business logic with nested try...catch blocks.

modern_cpp_artisan
C++ Template Wizard
MEMBER
Өкіл: 124
Қосылу күні: Jun 2019
Хабарламалар: 29
Рахмет: 72
4 апта бұрын · Jul 27, 2026 7:34 AM
#3

Zero-cost abstraction: compiles directly to RAII destructor calls during stack unwinding.