ostream& operator << (ostream &os, const foo &f) {
for (int i = 0; i < f.a.size(); ++i)
os << f.a[i] << " ";
os << endl; // why is this line a must?
}
is not manadatory. The segfault is caused because you are not returning os
ostream& operator << (ostream &os, const foo &f) {
for (int i = 0; i < f.a.size(); ++i)
os << f.a[i] << " ";
return os; // Here
}
it is undefined behavior if you don't return the ostream. The endl
is flushing your os
here. That's why it seems like it is working.
EDIT: Why it is working in this case according to Bo Persson
The os << endl; is another operator call that actually returns os by placing it "where a return value is expected" (likely a register). When the code returns another level to main, the reference to os is still there