title: Redirecting std::cout
body: <p>I need a class that redirects one ostream to another ostream during the lifetime of its object. After some tinkering I came up with this:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  
  
  class ScopedRedirect
  {
  public:
      ScopedRedirect(std::ostream &amp; inOriginal, std::ostream &amp; inRedirect) :
          mOriginal(inOriginal),
          mRedirect(inRedirect)
      {
          mOriginal.rdbuf(mRedirect.rdbuf(mOriginal.rdbuf()));
      }
  
      ~ScopedRedirect()
      {
          mOriginal.rdbuf(mRedirect.rdbuf(mOriginal.rdbuf()));
      }    
  
  private:
      ScopedRedirect(const ScopedRedirect&amp;);
      ScopedRedirect&amp; operator=(const ScopedRedirect&amp;);
  
      std::ostream &amp; mOriginal;
      std::ostream &amp; mRedirect;
  };
  
  
  int main()
  {
      std::cout &lt;&lt; "Before redirect." &lt;&lt; std::endl;
      std::ofstream filestream("redirected.txt");
      {
          ScopedRedirect redirect(std::cout, filestream);
          std::cout &lt;&lt; "During redirect." &lt;&lt; std::endl;
      }
      std::cout &lt;&lt; "After redirect." &lt;&lt; std::endl;
  
      return 0;
  }
  </code></pre>
  
  <p>It seems to work fine. However, it's weird that the following line is repeated in <em>both</em> the constructor and destructor:</p>
  
  <pre><code>mOriginal.rdbuf(mRedirect.rdbuf(mOriginal.rdbuf()));
  </code></pre>
  
  <p>I think it's correct, but I would like to verify with the SO community. Can you find any errors or dangers in this code?</p>
  
  Edit
  
  <p>Make non-copyable.</p>