C++ 如果没有endl,则重载ostream运算符分段错误 class-foo{ 公众: friend ostream&运营商

C++ 如果没有endl,则重载ostream运算符分段错误 class-foo{ 公众: friend ostream&运营商,c++,vector,operator-overloading,ostream,C++,Vector,Operator Overloading,Ostream,如果不返回ostream,这是一种未定义的行为。endl正在刷新您的os。这就是为什么它似乎在工作 编辑:根据Bo Persson的说法,为什么它在这种情况下有效 操作系统在这里没有返回隐式的int。它非常清楚地指定为返回ostream&。因此,如果没有return语句,您将得到函数后堆栈上正确位置的任何垃圾。使用os@honk中没有隐式int没有从非空> 函数返回某些东西,这只是一个未定义的行为,句号。@戴夫,你必须这样做。只是一些编译器,无论什么选项都不能告诉你你做了错误。从N33 37(C

如果不返回ostream,这是一种未定义的行为。
endl
正在刷新您的
os
。这就是为什么它似乎在工作

编辑:根据Bo Persson的说法,为什么它在这种情况下有效


操作系统在这里没有返回隐式的
int
。它非常清楚地指定为返回
ostream&
。因此,如果没有
return
语句,您将得到函数后堆栈上正确位置的任何垃圾。使用
os@honk中没有隐式
int
没有从非<代码>空> <代码>函数返回某些东西,这只是一个未定义的行为,句号。@戴夫,你必须这样做。只是一些编译器,无论什么选项都不能告诉你你做了错误。从N33 37(C++ C++ 11的初稿)<代码>“函数的结尾流等于一个代码<返回/<代码>没有值;这导致返回值函数中的未定义行为。”我猜编译器可能不认为这是错误的原因是有其他合法的方法来退出函数(例如抛出异常)。.@Dave-The
os为什么从来没有人关心检查有问题的代码?编译器应该警告您这类错误-“…警告:函数中没有返回非void[-Wreturn type]的return语句”请参见}^
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;
}
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?
}
ostream& operator << (ostream &os, const foo &f) {
    for (int i = 0; i < f.a.size(); ++i)
        os << f.a[i] << " ";
    return os; // Here
}