Re: Stream behavior that I don't understand
dasjotre wrote:
Alberto wrote:
I'm trying to put a string creation in a single statement.
The code to do so is ugly but I was hoping in a definite behavior.
static_cast<ostringstream&>(ostringstream() << "hello").str()
It is not only ugly it is simply wrong.
operator << is defined in basic_ostream, it returns basic_ostream, you
can't static_cast basic_ostream into ostringstream, basic_ostream
doesn't have str() function.
Sorry, but you missed a point there: all inserters return the original
stream. Further, all things in that context are passed by reference, so you
can be sure that the returnvalue of the insert operation is the same
stream. However, the type of the stream was reduced to the type of the
baseclass, which is why Alberto is using a static_cast to a reference to
the derived class.
That code looks a bit hackish (and at least deserves being given a nicer
interface) but otherwise it is completely correct (well, I'm not sure about
the weird behaviour the OP is experiencing)!
Actually this code do not work,
the resulting string is "0x804c950"
This looks like the address of a stack variable on at least some systems...
Anyway, what is wrong with
std::ostringstream out;
out<<"hello";
std::string s = out.str();
something as generic as this is typically written like this:
template<...>
...
...and then fits cleanly into a line without disturbing the flow with
temporary objects etc. ;)
If you can live with its behaviour, I'd suggest using boost::lexical_cast,
which does just that (and a bit better), otherwise roll your own.
Uli
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]