Developer knowledge network · moderated exchange

Сообщество UnreliableCode

Сообщество разработчиков, обратного проектирования и кодирования

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.