c++ - 如果没有 endl,则重载 ostream 运算符段错误

标签 c++ vector operator-overloading ostream

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;
}

上面代码中,如果去掉标记的那一行,会出现segment fault错误,谁能解释一下为什么?

最佳答案

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?
}

不是强制性的。段错误是因为您没有返回 os

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

如果您不返回 ostream,则为未定义行为。 endl 正在刷新您的 os。这就是它看起来有效的原因。

编辑:根据 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

关于c++ - 如果没有 endl,则重载 ostream 运算符段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15788672/

相关文章:

c++ - QSqlQuery 未定位在有效记录上

c++ - 基于对 vector 中第一个元素的降序排序没有给出期望的结果

c++ - 我应该如何在 C++ 中实现这些 vector ?它与 vector 有关的纬度和经度

c++ - 运算符重载。 q = q1+q2,q1 被修改,但我希望 q1 和 q2 保持不变

C++ IDE 在不重新编译的情况下检测语法错误?

c++ - 通过 C++ 中的另一个结构成员访问结构

r - 计算向量中具有 x 值的元素数量

c++ - C++ 是否会自动转换某些操作重载?

c++ - 在 C++ 中重载二元关系运算符的正确方法

c++ - 如何最好地测试 Mutex 实现?