Overloaded ostream operator segmentation fault if no endl

时间秒杀一切 提交于 2019-12-06 01:41:38

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/15788672/overloaded-ostream-operator-segmentation-fault-if-no-endl

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!