Strange behavoiur of ostringstream (tested on g++3.3.5/4.0.2)
Howard Hinnant
hhinnant@apple.com
Sat Jan 28 14:34:00 GMT 2006
On Jan 28, 2006, at 4:14 AM, Wladimir Mutel wrote:
> #define SFORMAT(e) ((dynamic_cast<const ostringstream&>
> (ostringstream() << e)).str())
>
> int main(int argc, char* argv[])
> {
> cout << SFORMAT("2 x " << " 2 = " << 2*2);
> return 0;
> }
>
> When I compile and run it, the first string constant ("2 x ") is
> printed as pointer in hexadecimal form. The second constant
> (" 2 = ") prints as it should.
> ltrace shows that first one is printed by
This is unfortunately standard behavior. In a nutshell, rvalue
streams are ill-supported in C++ today. When your macro operates on
ostringstream() << e, the ostringstream() is an rvalue, and this
leads to the behavior you're seeing.
Workarounds: You could cast your rvalue to an lvalue (say ostream&)
before applying the operator <<.
Hope: I'm fighting tooth and nail to get this behavior changed for C+
+0X, and right now it is looking promising:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2004/n1690.html#Use
%20of%20Rvalue%20Streams
This link also contains another workaround that would look like
(untested):
#define SFORMAT(e) ((dynamic_cast<const ostringstream&>(ostringstream
().flush() << e)).str())
The C++0X fix involves a language change, so it is not as simple as
just fixing the library (the compiler needs to change too).
-Howard
More information about the Libstdc++
mailing list