Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneral way to reset a member variable to its original value using the stack?
    primarykey
    data
    text
    <p>I came across a class instance function that needed to temporarily change a class instance variable, and then restore it when the function completed. The function had return statements all over the place, and before each return there was a restoring statement. That seemed messy to me, not to mention scary when a exception is thrown.</p> <p>As an improvement I came up with this generalization using a inner class definition. Here is a sample driver program (class restorer).</p> <pre><code>class Unwind { private: bool b_active_; ///&lt; the thing I want to be restored template&lt;typename T&gt; 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&lt;bool&gt; trust_in_the_stack(&amp;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 &lt;&lt; "deepest" &lt;&lt; endl; out("d end"); } void out(const std::string&amp; msg) { std::cout &lt;&lt; msg &lt;&lt; ": " &lt;&lt; b_active_ &lt;&lt; std::endl; } }; int main() { Unwind u; u.a(); return 0; } </code></pre> <p>The output using g++ 4.2.3 (-Wall) was:</p> <pre> a in: 0 b in: 0 c in: 1 d in: 1 deepest d end: 1 c end: 1 b inner end: 1 b end: 0 a end: 0 </pre> <p>Which is what I expect at "b end".</p> <p>I felt that defining the class restorer inside the class Unwind helps to discourage misuse.</p> <p>My question is, is there a general and safer way to do this? I am worried about lifetime issues.</p> <p>Edit: Please assume that there are no threads, but "downstream" methods on the stack that change behavior based on this b_active_ flag.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload