Re: assignment in if statement
In message <1146245313.177998.97930@j33g2000cwa.googlegroups.com>,
cole.harvey@yahoo.com writes
Hi all,
I am trying to minimize dynamic_cast by doing the following:
How is the code below minimising the use of dynamic_cast? I.e. what
other options that use it more have you rejected? (E.g. is the ordering
of your "if ... " tests putting the most frequent cases first?)
foo* myFoo = NULL;
bar* myBar = NULL;
blah* myBlah = NULL;
// for each pointer in a list: pointer
myFoo = NULL;
// these initializations are not needed
// your dynamic_casts will set up the pointers to 0
// or non-zero when needed
myBar = NULL;
myBlah = NULL;
if(myFoo = dynamic_cast<foo*>(pointer) && myFoo != NULL) {
// Do it
}
else if(myBar = dynamic_cast<bar*>(pointer) && myBar != NULL) {
// Do it
}
else if(myBlah = dynamic_cast<blah*>(pointer) && myBlah != NULL) {
// Do it
}
// end loop
So will the compiler do something smart and still call dynamic_cast on
each pointer? And will myFoo = dynamic_cast<foo*>(pointer) return
true, or do I need to use OR (||) instead of AND (&&)? Any other
comment are welcom.
Thanks.
Assuming that there is no inheritance relationship between foo, bar, and
blah, perhaps what you want is:
// loop start
if ( dynamic_cast<foo*>(pointer) || dynamic_cast<bar*>(pointer) ||
dynamic_cast<blah*>(pointer) ) // line wrapped by mailer
{
// Do it
}
// loop end
or, if you need the pointers in the loop body, then:
foo *myFoo;
bar *myBar;
blah *myBlah;
// loop start
if ( myFoo = dynamic_cast<foo*> (pointer)
|| myBar = dynamic_cast<bar*> (pointer)
|| myBlah = dynamic_cast<blah*>(pointer)
)
{
// Do it
}
// loop end
(The example code above uses the so-called "short-circuit" evaluation of
expressions using the "||" operator.)
If there is a public inheritance relationship between any of foo, bar,
and blah, then use of nested "if ... else" and ordering the tests base
--> derived might be faster (since if the pointer does not point to a
base object, neither does it point to a derived one). However, if a
derived object is by far the most common case, then putting this test
first could minimise the dynamic_cast invocations.
--
Alec Ross
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]