D pointers

Lars Knoll lars at trolltech.com
Tue Oct 4 08:29:30 BST 2005

On Tuesday 04 October 2005 05:10, George Staikos wrote:
> On Monday 03 October 2005 20:48, Thiago Macieira wrote:
> > George Staikos wrote:
> > >  struct oldPixmapType { QPixmap a, b; };
> > >  mutable union {
> > >    struct {
> > >      QPixmap *icon, *miniIcon;
> > >    } pm;
> > >    char unused[sizeof(oldPixmapType)];
> > >  } aIconPixmap; // KDE4: remove me
> > >
> > >  Here we were even able to reuse the space so we didn't need to add to
> > > the d-pointer.
> >
> > That's really ingenious. I hadn't thought of that!
> >
> > However, even though that guarantees the proper sizeof, it doesn't
> > guarantee __alignof and, hence, the necessary padding.
> >
> > You can solve that by adding one element to the union which has the same
> > alignment requirements that QPixmap has. The hard part is figuring out
> > which one that is.
> >
> > So in general I don't think it's not a good idea to replace complex types
> > with POD. The conclusion I come to is: if you're going to place a
> > variable outside the private class, at least use POD types.
>   I seem to recall that we went through this and determined that alignment
> was going to be correct so we didn't need to do anything different.  Well
> maybe until we run on 128-bit systems?
>   Actually don't the pointers guarantee we are aligned properly anyway?

You are mostly safe here. But just a look at the code above shows you why 
variables should be in the d-pointer and not in the class itself. It is a 
rather evil hack and should only be used as a last resort. Nothing you would 
want to use on a regular basis because (a) it takes you a long time (and a 
lot of experience) to verify that you really didn't break BC, and (b) it's 
really ugly and makes the code very hard to read and understand.

If the variable had been in the d-pointer, we could have just freely replaced 
it without even having to think half a minute on how to solve this.

Maintainability is one of the most important things in library code, 
especially in an open source project.


More information about the kde-core-devel mailing list