Thomas J. Gritzan
10/19/2008 8:23:00 PM
DeveloperDave wrote:
> On Oct 19, 7:34 pm, red floyd <no.spam.h...@example.com> wrote:
>> This is a memory leak. Why are you newing message? And why are you not
>> deleteing it? It should simply be declared as a local variable:
>>
>> ostringstream message;
>>
>> Let me guess, you're coming from Java?
>
> Guys, I'm not coming from java, and I don't want to know that I should
> always call delete with new (I know this already). This also isn't
> the final code, it is an example to illustrate my problem. Why not
> comment that the "..." will cause the code not to compile as well?
The point wasn't to use delete, but not using 'new' at all for a
variable that is only locally used. If you 'new' the ostringstream,
there's no point in avoiding the string copy.
> The question is:
>
> is it possible to use the member variables to construct a formatted
> string, i.e.
> Something like
>
> "Orgin:%s\nType:%s\nBody:%s\n"
Yes,
> Replacing the %s with my member variables, "orgin", "type", and
> "body", but without storing these in a new string i.e. not storing the
> same information twice.
Without storing the complete string? That depends on what you want to do
with the string.
For only outputting it to console (or file), you could implement a print
function that outputs to ostream&:
RequestMessage::print(std::ostream& message) const
{
message << origin << '\n'
<< "Type:" << type << '\n'
<< "Body:" << body << endl;
}
That way, a client could pretty print the object to cout, to a file
stream, a memory stream or any other custom stream.
--
Thomas