"Earl Purple" <ea********@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.com
John Carson wrote: "Dervish" <DA*******@yandex.ru> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com static_cast<ostringstream&>(ostringstream("String" )<<3).str()
To make this work I have added seekp:
(static_cast<ostringstream&>((ostringstream("Strin g").seekp(0,ios::end)
<< 3))).str()
What "works" depends on what the objective is, on which the OP was
not explicit. If the objective is to add a 3 to the end of "String",
then you are right. You can, incidentally, make do with less
brackets:
static_cast<ostringstream&>(ostringstream("String" ).seekp(0,ios::end)<<
3).str()
Do not cast away what the compiler tells you is not allowed. The
compiler is telling you that for a reason.
ostringstream("String") creates a temporary. Now you can call str() on
it because that is a const function. But you cannot call << 3 because
that is a non-const function - it modifies the temporary. And that is
undefined behaviour.
The reason for the non-compilation is not because a temporary has been
modified. Modifying a temporary is perfectly legal. You may note that the
following argument compiles without warnings:
string("String").append(" extra bit")
The compilation fails because operator<< is inherited from ostringstream's
base class of basic_ostream<char> and thus operator<< returns a reference to
this base class of basic_ostream<char> rather than a reference to
ostringstream. basic_ostream<char> has no str() member function and that is
the error message given --- nothing about modifying a temporary. The cast is
a downcast, made with knowledge that the object referenced is indeed an
ostringstream and not merely a basic_ostream<char>.
--
John Carson