why do not the comma, logical address, AND and logical OR administrators be over...
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.
why do not the comma, logical address, AND and logical OR administrators be overloaded in c ++?
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.
logical operators
&&
and||
The builtin versions exhibit short circuit optimisation: in an expression likea && b
,a
is evaluated first and only iftrue
,b
is also evaluated; similarly, ina || b
,a
is evaluated first and only iffalse
,b
is also evaluated. Overloaded operators&&
and||
don't have short-circuit optimisation (botha
andb
are always evaluated) and also the order of evaluation of the arguments is not specified.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 thenb
. With an overloaded comma operator, this guarantee is lost (and instead the function parameter mechanism comes into play).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 codestruct 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 infoo()
, but the human writing the code offoo()
cannot know this or which operator will be used. This problem is avoided when usingstd::addressof
as forptr2
, which obtains the equivalent of the builtin address-of operator, even iftype
has an overloaded&
operator.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK