Question

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 < f.a.size(); ++i)
        os << f.a[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 removed, there will be a segment fault error, can someone explain why?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top