title: Obtain a std::ostream either from std::cout or std::ofstream(file)
body: <p>how do I bind a <code>std::ostream</code> to either <code>std::cout</code> or to an <code>std::ofstream</code> object, depending on a certain program condition? Although this invalid for many reasons, I would like to achieve something that is semantically equivalent to the following:</p>
  
  <pre><code>std::ostream out = condition ? &amp;std::cout : std::ofstream(filename);
  </code></pre>
  
  <p>I've seen some examples that are not exception-safe, such as one from <a href="http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html" rel="noreferrer">http://www2.roguewave.com/support/docs/sourcepro/edition9/html/stdlibug/34-2.html</a>:</p>
  
  <pre><code>int main(int argc, char *argv[])
  {
    std::ostream* fp;                                           //1
    if (argc &gt; 1)
       fp = new std::ofstream(argv[1]);                         //2
    else
       fp = &amp;std::cout                                          //3
  
    *fp &lt;&lt; "Hello world!" &lt;&lt; std::endl;                         //4
    if (fp!=&amp;std::cout) 
       delete fp;
  }
  </code></pre>
  
  <p>Does anyone know a better, exception-safe solution?</p>