Why are bitwise shifts (<< and>>) used for cout and cin?

后端 未结 13 1718
眼角桃花
眼角桃花 2020-12-02 16:16

Question is in the title really; I\'m sure there is something logical, but for now I\'m stumped!

13条回答
  •  生来不讨喜
    2020-12-02 16:53

    Because they had more or less a reasonable precedence and looked good. In C++ you cannot create new operators or change their precedence or grouping rules, you can only overload existing ones and changing what they actually do.

    The choice of << and >> has some unfortunate side effect because it's somehow pushing the idea that the output will be done respecting the order. While this is true for the actual output thanks to a clever chaining trick it's however false for the computations involved and this is very often surprising.

    To be more specific writing

    std::cout << foo() << bar() << std::eol;
    

    does NOT imply that foo will be called before bar.

    EDIT

    With C++17 the sequence problem has been "fixed". Now the order of evaluation is specified to be left-to-right for << and >> operators. There are still places in C++ where the order of evaluation is unspecified (or even non-existing meaning that evaluation can be interleaved) but a few common cases now behave in a predictable and portable way see this answer .

提交回复
热议问题