Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Unwind {
- private:
- bool b_active_; ///< the thing I want to be restored
- template<typename T>
- class restorer {
- T* ref_;
- T save_;
- public:
- restorer(T* perm) : ref_(perm), save_(*ref_) {};
- ~restorer() { *ref_ = save_; }
- };
- public:
- Unwind() : b_active_(false) {};
- void a() { out("a in"); b(); out("a end"); }
- void b() {
- out("b in");
- {
- restorer<bool> trust_in_the_stack(&b_active_); // "restorer" created on the stack
- b_active_ = true; // change b_active_ only while "within" b()
- c();
- out("b inner end");
- }
- out("b end");
- }
- void c() { out("c in"); d(); out("c end"); }
- void d() { out("d in"); cout << "deepest" << endl; out("d end"); }
- void out(const std::string& msg) {
- std::cout << msg << ": " << b_active_ << std::endl;
- }
- };
- int main() { Unwind u; u.a(); return 0; }
- template<typename T>
- class restorer {
- T& ref_;
- T save_;
- public:
- restorer(T& perm) : ref_(perm), save_(ref_) {};
- ~restorer() { ref_ = save_; }
- };
- template<typename T>
- class restorer {
- T& ref_;
- T save_;
- public:
- restorer(T& perm) : ref_(perm), save_(ref_) {};
- ~restorer() { ref_ = save_; }
- };
- /// c++ code sample
- #ifndef UTIL_RESTORER_HPP
- #define UTIL_RESTORER_HPP
- namespace Utility {
- /// A Restorer instance ("inst") uses the stack to restore a saved
- /// value to the named variable when the instance "inst" goes out of
- /// scope.
- ///
- /// Restorer is designed to be an auto variable, not allocated on any
- /// other memory resource like a heap or in-place.
- template<typename T>
- class restorer {
- T& ref_;
- T save_;
- public:
- restorer(T& perm) : ref_(perm), save_(perm) {}
- ~restorer() { ref_ = save_; }
- };
- }//NAMESPACE
- #endif//UTIL_RESTORER_HPP
Add Comment
Please, Sign In to add comment