Overloading logical operators considered bad practice?

前端 未结 7 679
星月不相逢
星月不相逢 2021-01-11 13:40

Is it a bad idea to overload &&, || or comma operator and Why?

7条回答
  •  攒了一身酷
    2021-01-11 14:37

    I wouldn't overload operator&& or operator||. Even if you define a class that gives rise to a Boolean algebra (finite sets, for example), it would probably be a better choice to overload operator& and operator|.

    The reason is that C++ programmers expect special semantics for operator&& and operator||: they are short-circuited, i.e. don't evaluate their right-hand argument if not necessary. You can't get this behavior by overloading, since you'll be defining a function.

    Overloading operator, has been done in e.g. the Boost.Assign library. This is also the only example of its overloading that I know, and I've never even considered overloading it myself. You'd better have a very specific use case for it where no other operator is suited.

提交回复
热议问题