Overloaded statement segmentation error if no endl

class foo { public: friend ostream& operator << (ostream &os, const foo &f); foo(int n) : a(n) {} private: vector <int> a; }; ostream& operator << (ostream &os, const foo &f) { for (int i = 0; i < fasize(); ++i) os << fa[i] << " "; os << endl; // why is this line a must? } int main(void) { foo f(2); cout << f << endl; return 0; } 

In the above code, if the marked line is deleted, a segment error error will occur, can someone explain why?

+6
source share
1 answer
 ostream& operator << (ostream &os, const foo &f) { for (int i = 0; i < fasize(); ++i) os << fa[i] << " "; os << endl; // why is this line a must? } 

not manorial. Segfact is caused by the fact that you do not return os

 ostream& operator << (ostream &os, const foo &f) { for (int i = 0; i < fasize(); ++i) os << fa[i] << " "; return os; // Here } 

this behavior is undefined unless you return ostream. endl cleans your os here. That is why it seems to work.

EDIT: Why does he work in this case according to Bo Persson

. os <arps; this is another statement that actually returns os by placing it "where the expected value is expected" (probably case). When the code returns another level in main, the link to os is still there

+16
source

All Articles