简体   繁体   中英

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 (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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM