Skip to main content
gamedev.net
🔒 Locked

Returning a stream from a function

Started by tifkagh 1 reply 550+ views
Original Post
tifkagh
tifkagh
I have a function that dumps some details that I would like to write to a file. Currently the function directs all its output to cout and my ofstream is not available to the function. My approach to the problem was as follows: Firstly redeclare the function so that it returns an ostream: std::ostream mbsGType::DumpActions() Next declare and ostream within the function and use it as the return value: ostream Return; Return << " Moves made: "; Return.width(3); Return << NumActions; ... return Return; My thinking was that I could then call the function as follows: cout << objgtype->DumpActions(); However, the compiler does not like my declaration of Return. Is this the right approach to solving this problem? If so, why does the declaration of Return not work? Thanks, Garvin.
glassJAw
glassJAw
ostream has a constructor argument.
jermz
jermz
I would have the function accept a reference to an ostream as an argument. Otherwise, each call to DumpActions() will locally create its own ostream which will promptly be copy-constructed and destructed at function exit. Seems inefficient and a bad delegation over the ostream''s lifetime.


void Object::DumpActions(ostream& os)
{
os << " Moves made: ";
os.width(3);
os << numActions;
}

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.