ostream& operator<< segfaults without flush()
I have a custom class for which I've defined a custom cast operator char()
, call it A
. Now, say I want an array of this class but with added functionality so I define a new class B
to achieve this with a member variable array
of type std::vector<A>
.
One of the things I want B
to handle is printing its data to screen so I create a friend
function
ostream& operator<<(ostream& out, const B& b)
{
// invoking custom cast works fine here
for(int i=0;i<array.size();++i) out.put((char)array[i]);
// without the following out.flush() we get segfault
out.flush()
}
For some reason when I omit the out.flush()
statement at the end it causes a segmentation fault. I would rather not have the flush in there because it should be up to the user to choose when to flush the stream 开发者_JAVA技巧(I believe?) so can anybody please clarify why it crashed without it?
Thanks!
You have to return something there. Certainly the stream you've been provided, so you should:
return out;
as the last line of the operator. Note that, maybe by chance, calling out.flush()
made some register (say EAX) to hold the value of the stream, thus being returned (as per standard calling convention), and this is what the caller was expecting. BUT you have to add that last return
for sure.
精彩评论