code_junkie

General way to reset a member variable to its original value using the stack?

Nov 11th, 2011
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.70 KB | None | 0 0
  1. class Unwind {
  2. private:
  3. bool b_active_; ///< the thing I want to be restored
  4. template<typename T>
  5. class restorer {
  6. T* ref_;
  7. T save_;
  8. public:
  9. restorer(T* perm) : ref_(perm), save_(*ref_) {};
  10. ~restorer() { *ref_ = save_; }
  11. };
  12. public:
  13. Unwind() : b_active_(false) {};
  14. void a() { out("a in"); b(); out("a end"); }
  15. void b() {
  16. out("b in");
  17. {
  18. restorer<bool> trust_in_the_stack(&b_active_); // "restorer" created on the stack
  19. b_active_ = true; // change b_active_ only while "within" b()
  20. c();
  21. out("b inner end");
  22. }
  23. out("b end");
  24. }
  25. void c() { out("c in"); d(); out("c end"); }
  26. void d() { out("d in"); cout << "deepest" << endl; out("d end"); }
  27. void out(const std::string& msg) {
  28. std::cout << msg << ": " << b_active_ << std::endl;
  29. }
  30. };
  31.  
  32. int main() { Unwind u; u.a(); return 0; }
  33.  
  34. template<typename T>
  35. class restorer {
  36. T& ref_;
  37. T save_;
  38. public:
  39. restorer(T& perm) : ref_(perm), save_(ref_) {};
  40. ~restorer() { ref_ = save_; }
  41. };
  42.  
  43. template<typename T>
  44. class restorer {
  45. T& ref_;
  46. T save_;
  47. public:
  48. restorer(T& perm) : ref_(perm), save_(ref_) {};
  49. ~restorer() { ref_ = save_; }
  50. };
  51.  
  52. /// c++ code sample
  53. #ifndef UTIL_RESTORER_HPP
  54. #define UTIL_RESTORER_HPP
  55.  
  56. namespace Utility {
  57.  
  58. /// A Restorer instance ("inst") uses the stack to restore a saved
  59. /// value to the named variable when the instance "inst" goes out of
  60. /// scope.
  61. ///
  62. /// Restorer is designed to be an auto variable, not allocated on any
  63. /// other memory resource like a heap or in-place.
  64. template<typename T>
  65. class restorer {
  66. T& ref_;
  67. T save_;
  68. public:
  69. restorer(T& perm) : ref_(perm), save_(perm) {}
  70. ~restorer() { ref_ = save_; }
  71. };
  72.  
  73. }//NAMESPACE
  74. #endif//UTIL_RESTORER_HPP
Add Comment
Please, Sign In to add comment