title: The first string argument to a stringstream is saved as a pointer/garbage
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/8013900/printing-a-string-to-a-temporary-stream-object-in-c">Printing a string to a temporary stream object in C++</a><br>
    <a href="https://stackoverflow.com/questions/8287188/stdostringstream-printing-the-address-of-the-c-string-instead-of-its-content">std::ostringstream printing the address of the c-string instead of its content</a>  </p>
  </blockquote>
  
  
  
  <p>I'm trying to build up a string using stringstream, in the same way you'd use cout. This for something like a logging class. The issue I'm having is that if the first argument to the &lt;&lt; operator is a string, when I subsequently print out that stringstream with the stringstream::str() call, I get a garbage address, and not the string. This only occurs with the FIRST string. Subsequent strings are fine. Numbers are always fine. Here's the code:</p>
  
  <pre><code>    // class I use to print out the stream
      class StreamWriter
      {
      public:
          StreamWriter()
          {}
  
          ~StreamWriter()
          {
              std::string myMessage = m_stringstream.str();
              std::cout &lt;&lt; myMessage &lt;&lt; std::endl;
          }
  
          std::stringstream m_stringstream;
      };
  
      // macro for simplification
      #define OSRDEBUG (StreamWriter().m_stringstream)
  
      // actual use
      OSRDEBUG &lt;&lt; "Hello " &lt;&lt; "my " &lt;&lt; "name is Pris " &lt;&lt; 123456;
  
      // output
      0x8054480my name is Pris 123456
      0x8054480my name is Pris 123456
      0x8054480my name is Pris 123456
      0x8054480my name is Pris 123456
  </code></pre>
  
  <p>Could anyone shed some light on what's going on, and how I could get around the issue?</p>
  
  <p>EDIT:
  The following changes (in addition to padiablo's examples) works as well, maintaining the use of the class's destructor with the macro.</p>
  
  <pre><code>    // class I use to print out the stream
      class StreamWriter
      {
      public:
          StreamWriter()
          {   m_stringstream = new std::stringstream;   }
  
          ~StreamWriter()
          {
              std::string myMessage = m_stringstream.str();
              std::cout &lt;&lt; myMessage &lt;&lt; std::endl;
              delete m_stringstream;
          }
  
          std::stringstream * m_stringstream;
      };
  
      // macro for simplication
      #define OSRDEBUG *(StreamWriter().m_stringstream)
  </code></pre>
  
  <p>The original question still stands though, because it looks like it should work... and I think it's probably important to know when the times comes to put this into production-quality code.</p>