【问题标题】:Cascading the stream insertion operator doesn't work级联流插入运算符不起作用
【发布时间】:2017-03-22 20:12:57
【问题描述】:

我正在阅读一篇关于 Overloading the Stream Insertion Operator (<<) 的文章。它强调应该返回输出流对象以确保操作符正确级联。但是好像没有return,输出还是正确的,这里有什么问题?

#include<iostream>

class Rational
{
    friend std::ostream& operator<<(std::ostream&, const Rational&);

    private:
        int numerator;
        int denominator;
    public:
        Rational(int num, int den): numerator{num}, denominator{den} {}
};

std::ostream& operator<<(std::ostream& lhs, const Rational& rhs)
{
    lhs << rhs.numerator << "/" << rhs.denominator;
    //return lhs;
}

int main()
{
    Rational r1(3, 5);
    std::cout << "The value of r1 is " << r1 << std::endl; // After commenting return lhs; still works fine
}

【问题讨论】:

    标签: c++ c++11 return operator-overloading


    【解决方案1】:

    这是 UB,因为应该返回对象的函数在没有返回语句的情况下结束。它可能运作良好,但没有任何保证。

    来自标准,$6.6.3/2 The return statement [stmt.return]

    (强调我的)

    从构造函数、析构函数或具有 cv void 返回类型的函数的末尾流出等效于没有操作数的 return。否则,从main (basic.start.main) 以外的函数末尾流出会导致未定义的行为


    您可能希望查看来自clang 的结果;发出警告

    警告:控制到达非空函数[-Wreturn-type]的末尾

    并导致无限递归。

    【讨论】:

      【解决方案2】:

      事实上,该函数具有未定义的行为。它之所以起作用,可能是因为它将对流的引用存储在一个寄存器(例如 EAX)中,并且编译器使用该寄存器来传递返回值。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-10
        • 1970-01-01
        • 2022-10-06
        • 2022-06-21
        • 2015-07-29
        • 1970-01-01
        • 2016-01-27
        • 1970-01-01
        相关资源
        最近更新 更多