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.)
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!