如果没有endl,重载ostream运算符分段错误 [英] Overloaded ostream operator segmentation fault if no endl

查看:122
本文介绍了如果没有endl,重载ostream运算符分段错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  class foo {
public:
friend ostream&运算符<< (ostream& os,const foo& f);
foo(int n):a(n){}
private:
vector< int>一个;
};

ostream&运算符<< (ostream& os,const foo& f){
for(int i = 0; i os< f.a [i]<< ;
os<< endl //为什么这行是必须的?
}

int main(void){
foo f(2);
cout<< f<< endl
return 0;
}

在上面的代码中,如果标记行被删除,段错误,可以解释为什么吗?

解决方案

 运算符<< (ostream& os,const foo& f){
for(int i = 0; i os< f.a [i]<< ;
os<< endl //为什么这行是必须的?
}

不是manadatory。 segfault是因为你没有返回 os

  ostream&运算符<< (ostream& os,const foo& f){
for(int i = 0; i os< f.a [i]<< ;
return os; // Here
}

如果不返回ostream, endl 在此处刷新您的 os



b b b b b b b blockquote>

os< endl是另一个操作符调用,它实际上通过
返回os,将它置于预期返回值(可能是寄存器)。
当代码向main返回另一个级别时,对os的引用是
仍然存在



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?

解决方案

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

这篇关于如果没有endl,重载ostream运算符分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆