help-gplusplus
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: dynamic_cast from base to another parent of derived class


From: Boris
Subject: Re: dynamic_cast from base to another parent of derived class
Date: Wed, 4 Oct 2006 16:06:57 +0300

Boris wrote:
>> I wonder how you reached such a conclusion. Where on that page do
>> they say it does not work?
>
> The title is pretty clear I think: "dynamic_cast,throw, typeid don't
> work with shared libraries". :-) They are talking about template
> instantiations, vague linkage, not an exhaustive list, namesspaces
> etc. This all doesn't sound like adding a linker switch fixes all
> your problems. This sounds like be ready for all kind of problems.
>
> Anyway if I can downcast to the actual type and then back to its
> parent with the following code (no compilation error, no runtime
> error) why should a dynamic_cast to the parent l1 not work?
>
> if (typeid(b) == typeid(level2))
> {
>  const level2 *l2 = dynamic_cast<const level2*>(&b);
>  const level1 *l1 = l2;
> }

I changed the code to use boost::polymorphic_downcast instead of 
dynamic_cast:

if (typeid(b) == typeid(level2))
{
  const level1 *l1 = boost::polymorphic_downcast<const level1*>(&b);
}

With NDEBUG defined boost::polymorphic_downcast uses only static_cast - this 
works. Without NDEBUG defined dynamic_cast is used which doesn't work (as an 
assert fails).

Summary: Everything works with reinterpret_cast and static_cast or 
dynamic_cast when statically linked. It fails when dynamic_cast is used in a 
shared library. It can not be reproduced with a small test case as 
everything works then. The project I port to UNIX uses dynamic_casts in 
different files where some do work. There must be some more conditions which 
make g++ produce wrong code and which make some dynamic_casts fail 
constantly.

Boris 




reply via email to

[Prev in Thread] Current Thread [Next in Thread]