title: Is there any way to extend the lifetime of a temporary object in C++?
body: <p>I wrote a scope guard which resets a value when the scope exits:</p>
  
  <pre><code>template &lt;class T&gt;
  struct ResetGuard
  {
      T old_value;
      T&amp; obj_to_reset;
      ResetGuard(T&amp; obj_to_reset, const T&amp; new_value) :
          old_value(obj_to_reset),
          obj_to_reset(obj_to_reset)
      {
          obj_to_reset = new_value;
      }
  
      ~ResetGuard() { obj_to_reset = old_value; }
  };
  </code></pre>
  
  <p>When this scope guard is returned from a function, is there any way to prevent the immediate destruction of the scope guard if it wasn't saved?</p>
  
  <p>For example:</p>
  
  <pre><code>int GLOBAL_VALUE = 0;
  ResetGuard&lt;int&gt; temporarily_set_global_value(int new_val) {
      return { GLOBAL_VALUE, new_val }; //updates the global variable
  }
  void foo() {
      //Ideally, someone calling this function
      //Wouldn't have to save the returned value to a local variable
      temporarily_set_global_value(15);
      std::cout &lt;&lt; "GLOBAL_VALUE is " &lt;&lt; GLOBAL_VALUE &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>The way it's written now, anyone calling one of the functions would have to remember to always save the ResetGuard to a local variable, otherwise it would immediately reset the value.</p>
  
  <h1>Some context around what I'm trying to do</h1>
  
  <p>I'm writing a library to format and manipulate strings. I have one global variable controlling how floating point numbers are formatted. I <em>know</em> that global variables are typically a terrible idea, but please bear with me.</p>
  
  <p>I made the decision to use a global variable carefully. The alternative to using a global variable would be to pass around the object containing the formatting specification. This option ultimately proved infeasible: my library is designed to work with any objects that provide a implicit conversion to <code>std::string</code>. There's no way to pass formatting options (or any parameters, really) to an implicit conversion function. Hence, I had to resort to using a global variable.  </p>