2

Possible Duplicate:
Why does writing to temporary stream fail?

I'm trying to derive a class from ostrginstream for some custom logging code. Oddly, the first thing written to the stream always gets mangled. Here's a minimal, self-contained demonstration program:

#include <iostream>
#include <sstream>
using namespace std;

class Test : public ostringstream
{
public:
    Test()  { ; }
    ~Test() { cerr << "!" << str() << "!" << std::endl; }
};

int main(void)
{
    Test() << "Hello" << ", " << "World";
}

Expected output is: !Hello, world!

Actual output is:

!0x8049d14, World!

I'm assuming something is wrong with the way I'm creating and using the temporary object.

If it can't easily be fixed, is there another way to get the same semantics? What I'm looking for is the ability to easily create an object, shift into it, and then do something with the complete message in the destructor. (The use case is custom logging code. The destructor will timestamp, check severity, and so on.)

Community
  • 1
  • 1
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • 4
    possible duplicate of [Why does writing to temporary stream fail?](http://stackoverflow.com/questions/5179522/why-does-writing-to-temporary-stream-fail) and [Printing a string to a temporary stream object in C++](http://stackoverflow.com/questions/8013900/printing-a-string-to-a-temporary-stream-object-in-c) – sth May 31 '12 at 23:51
  • `if (1) { Test f; f << "Hello" << ", " << "World"; }` works. But there's no way I can make that as easy to invoke. – David Schwartz May 31 '12 at 23:54
  • C++0x (gcc-4.5.1) [prints the expected output](http://ideone.com/Yd16d). Perhaps a change in C++11? – Jesse Good May 31 '12 at 23:55
  • [CashCow's wrapper](http://stackoverflow.com/a/5180302/721269) works like a charm. Well, like a charm would work if charms worked. – David Schwartz May 31 '12 at 23:59
  • @JesseGood, a comment on CashCow's answer: `The upcoming C++0x will solve this problem with an extra operator<< overload that takes an rvalue reference and returns an lvalue reference. Then the flush() trick will not be needed anymore.` – chris Jun 01 '12 at 00:01
  • @chris: Thanks! I should read the links more carefully :) – Jesse Good Jun 01 '12 at 00:02

0 Answers0