Overloading logical operators considered bad practice?

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

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

相关标签:
7条回答
  • 2021-01-11 14:16

    You shouldn't overload any operators in a way that is surprising. :-)

    If you can do it in a way that makes sense (not only to you), it is fine to do so.

    Like others have said, the logical operators are special in that they have the effect of lazy evaluation. So your overloads should probably preserve this lazy effect, like with expression templates, or only be used where people don't expect this effect anyway.

    0 讨论(0)
  • 2021-01-11 14:16

    I'd say it depends on what your overloads are doing. For example, && and || are expected to work as logical conditions, so if your overload semantics work somehow differently, they can confuse other people (or even yourself, if you don't use them for a while and forget what they do). Consider what you would expect the operators to do if you wouldn't know how they are overloaded and if it would be clearer to just use normal methods instead.

    0 讨论(0)
  • 2021-01-11 14:20

    Its bad idea except situations when your classes represents some logic entity, because overloaded operators will disorientate and can cause new bugs in code.

    0 讨论(0)
  • 2021-01-11 14:21

    As the others have said, missing lazy evaluation is the main reason to avoid overloading logical operators.

    However, there is one very good reason to overload them: Expression templates. The Boost.Lambda library does this, and it's very useful!

    0 讨论(0)
  • 2021-01-11 14:28

    For overloading the logical operators in C++, the operands must be evaluated, which isn't the way things normally work with short circuiting of built-in types.

    Look at the below link.

    • Don't overload logical operators in C++
    0 讨论(0)
  • 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.

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