LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Programs · Question 6

Scope guard that runs a lambda on exit in C++ Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Write a ScopeGuard class template that stores a lambda and calls it in its destructor unless dismissed; use it to roll back a two-step transfer when the second step fails.

Solution
main.cpp
#include <iostream>
#include <stdexcept>
#include <string>
#include <utility>

template <typename F>
class ScopeGuard {
    F f_;
    bool active_ = true;
public:
    explicit ScopeGuard(F f) : f_(std::move(f)) {}
    ~ScopeGuard() { if (active_) f_(); }
    void dismiss() { active_ = false; }
    ScopeGuard(const ScopeGuard&) = delete;
    ScopeGuard& operator=(const ScopeGuard&) = delete;
};

int from = 1000, to = 0;

void transfer(int amount, bool fail_second_step) {
    from -= amount;
    ScopeGuard undo([amount] { from += amount; std::cout << "  rolled back\n"; });
    if (fail_second_step) throw std::runtime_error("credit failed");
    to += amount;
    undo.dismiss();                      // success: keep the debit
}

int main() {
    transfer(300, false);
    std::cout << from << ' ' << to << '\n';
    try { transfer(200, true); } catch (const std::exception& e) { std::cout << "  error: " << e.what() << '\n'; }
    std::cout << from << ' ' << to << '\n';
    return 0;
}

Output Verified by compiling and running

700 300
  rolled back
  error: credit failed
700 300

The lambda describes how to undo the first step; the destructor runs it during stack unwinding when the exception escapes. dismiss() cancels it on success. (std::scope_exit in the Library Fundamentals TS works the same way.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links