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.