DRAFT document on coding conventions in kde libraries
Thiago Macieira
thiago at kde.org
Mon Mar 6 12:22:01 GMT 2006
Mirko Boehm wrote:
>On Monday 06 March 2006 09:40, Allan Sandfeld Jensen wrote:
>...
>
>> It is unreliable across shared libaries. If you have a non-QObject
>> based heirachy you should implement your own type-system rather than
>> rely on dynamic_cast.
>
>Can you give a bit of information about
>- on what platforms such problems arise
>- and what compiler versions are affected?
This problem can occur if you're trying to cast to a class whose typeinfo
struct is inlined. In this case, both RTLD_LAZY and
hidden-inline-visibility cause the class to point to its local copy of
the typeinfo, instead of the global one. So it won't match when you
dynamic cast.
Example:
in foo.h:
class Base
{
virtual ~Base(); // Base::~Base is defined somewhere
};
class Derived: public Base
{
virtual ~Base() { }
virtual void foo() { std::cout << "Hello, world!"; }
};
in module.cpp:
Base* createClass()
{
return new Derived;
}
in application.cpp:
[...]
Base *ptr;
// somehow call createClass via dlopen+dlsym
Derived *dptr = dynamic_cast<Derived*>(ptr);
The last line will fail always. The reason is that createClass() called
the inlined Derived::Derived() constructor, which in turn assigned its
own local copy of "typeinfo for Derived" to the class.
When you try to cast "ptr" to "Derived", it'll use yet another "typeinfo
for Derived". Since they aren't the same object, the cast will always
fail.
Also note that static_cast<> will work.
--
Thiago Macieira - thiago (AT) macieira.info - thiago (AT) kde.org
PGP/GPG: 0x6EF45358; fingerprint:
E067 918B B660 DBD1 105C 966C 33F5 F005 6EF4 5358
1. On frumscafte, hwonne time_t wæs náht, se scieppend þone circolwyrde
wundorcræftlíge cennede and seo eorðe wæs idel and hit wæs gód.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 191 bytes
Desc: not available
URL: <http://mail.kde.org/pipermail/kde-core-devel/attachments/20060306/948d3a4b/attachment.sig>
More information about the kde-core-devel
mailing list