Re: operator= function
On Dec 4, 8:44 pm, Kira Yamato <kira...@earthlink.net> wrote:
On 2007-12-04 11:06:48 -0500, Rahul <sam_...@yahoo.co.in> said:
[...]
is not clear what you're testing for here. Code readability
should be highly sought for. Even with native data-types like
integers, it's better to write
if (n != 0) ...
than just
if (n) ...
Support for the "if (n)" notation is really just a historical
abherition. Originally, C didn't have a boolean type; you had
to simulate it with int. And of course, "if ( n )" *is* the
correct way to write a test of a boolean variable.
When bool was added to C++, the original proposal was also to
deprecate the implicit conversions of int to bool. In the end,
this was dropped, because it was felt that it would break way
too much code.
unless you worry about performance, at which I would think a
smart compiler would generate equivalent codes for both cases
anyway.
Even a dumb compiler. Even before bool, the compiler needs some
sort of boolean value to make a binary test. Internally, you
generally cannot simply make a conditional jump on an integral
value. (This wasn't necessarily true for older processors.)
The result is that if an expression is used in a boolean
context, and the top node is not a comparison (which sets the
processor's condition codes), the compiler inserts a node with
the comparison. Whether you write "if ( n )" or "if ( n != 0
)", the expression trees used to generate the code are normally
identical.
Also, don't overload the operator bool() just to support the
if-test. You might get yourself into trouble in other
situations with this implicit conversion.
My suggestion is to be explicit and have an method like
bool isValid() const;
so that your if statement reads more explicitly
if ((a=b).isValid()) ...
Don't do that either. With very few exceptions, a single
statement should to one, and only one thing, if you want your
code to be readable. An if statement is flow control, and so
shouldn't modify state.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34