11

why do not the comma, logical address, AND and logical OR administrators be over...

 3 years ago
source link: https://www.codesd.com/item/why-do-not-the-comma-logical-address-and-and-logical-or-administrators-be-overloaded-in-c.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

why do not the comma, logical address, AND and logical OR administrators be overloaded in c ++?

advertisements

Can someone please explain with examples why it is not a good practice to overload comma, address-of, logical AND, and logical OR operators in c++?


The underlying reason is that overloaded versions of these operators behave differently than the builtin versions. This can lead to substantial confusion (of humans) reading/writing code.

  1. logical operators && and || The builtin versions exhibit short circuit optimisation: in an expression like a && b, a is evaluated first and only if true, b is also evaluated; similarly, in a || b, a is evaluated first and only if false, b is also evaluated. Overloaded operators && and || don't have short-circuit optimisation (both a and b are always evaluated) and also the order of evaluation of the arguments is not specified.

  2. Comma operator The builtin version guarantees that the arguments are evaluated in the order they occur, i.e. in a,b a is evaluated first then b. With an overloaded comma operator, this guarantee is lost (and instead the function parameter mechanism comes into play).

  3. address-of operator There is a potential confusion between the builtin address-of operator & and the overloaded one when applied to objects of incomplete type. Consider this code

    struct type;            // forward declaration: type is (as of yet) incomplete
    
    #include <memory>
    void foo(type &obj)     // allowed: take object of incomplete type by reference
    {
      auto ptr1 = &obj;                  // address of obj -- or not?
      auto ptr2 = std::addressof(obj);   // always address of obj
    }
    
    // possibly in a different translation unit:
    struct type
    {
      type* operator&() { return nullptr; }
    };
    
    

    This code exhibits unspecified behaviour: the compiler can implement either version of the & operator in foo(), but the human writing the code of foo() cannot know this or which operator will be used. This problem is avoided when using std::addressof as for ptr2, which obtains the equivalent of the builtin address-of operator, even if type has an overloaded & operator.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK