What makes Scala's operator overloading “good”, but C++'s “bad”?

后端 未结 14 2073
悲哀的现实
悲哀的现实 2020-12-12 11:20

Operator overloading in C++ is considered by many to be A Bad Thing(tm), and a mistake not to be repeated in newer languages. Certainly, it was one feature specifically drop

相关标签:
14条回答
  • 2020-12-12 11:54

    There is nothing wrong with operator overloading. In fact, there's something wrong with not having operator overloading for numeric types. (Take a look at some Java code that uses BigInteger and BigDecimal.)

    C++ has a tradition of abusing the feature, though. An often-cited example is that the bitshift operators are overloaded to do I/O.

    0 讨论(0)
  • 2020-12-12 12:00

    This article - "The Positive Legacy of C++ and Java" - answers your question directly.

    "C++ has both stack allocation and heap allocation and you must overload your operators to handle all situations and not cause memory leaks. Difficult indeed. Java, however, has a single storage allocation mechanism and a garbage collector, which makes operator overloading trivial" ...

    Java mistakenly (according to the author) omitted operator overloading because it was complicated in C++, but forgot why (or didn't realize that it didn't apply to Java).

    Thankfully, higher level languages like Scala give developers options, while still running on the same JVM.

    0 讨论(0)
  • 2020-12-12 12:01

    I have never seen an article claiming that C++'s operator overloading is bad.

    User-definable operators permit an easier higher level of expressivity and usability for users of the language.

    0 讨论(0)
  • 2020-12-12 12:03

    However, it wouldn't seem to be qualitatively different to the operator overloading in C++, where as I recall operators are defined as special functions.

    AFAIK, There is nothing special in operator functions compared to "normal" member functions. Of course you only have a certain set of operators that you can overload, but that doesn't make them very special.

    0 讨论(0)
  • 2020-12-12 12:04

    The only thing known wrong in C++ is the lack of the ability to overload []= as a separate operator. This could be hard to implement in a C++ compiler for what is probably not an obvious reason but plenty worth it.

    0 讨论(0)
  • 2020-12-12 12:06

    Operator overloading in C++ is considered by many to be A Bad Thing(tm)

    Only by the ignorant. It is absolutely required in a language like C++, and it is noticeable that other languages that started off taking a "purist" view, have added it once their designers found out how necessary it is.

    0 讨论(0)
提交回复
热议问题