[Qt-interest] QList<T> conversion

Diez B. Roggisch diez.roggisch at ableton.com
Tue Feb 1 17:29:05 CET 2011


On Tuesday, February 01, 2011 02:31:02 pm Gustavo de Sá Carvalho Honorato 
wrote:
> On Fri, Jan 28, 2011 at 8:56 PM, Thiago Macieira <thiago at kde.org> wrote:
> > On Friday, 28 de January de 2011 19:58:12 Gustavo de Sį Carvalho Honorato
> > 
> > wrote:
> > > Hi,
> > > 
> > > is it possible to convert QList<A*> to QList<QObject*>, where A
> > > inherits from QObject? I would like to do this without create a new
> > > QList<QObject*> container and typecasting each element before add into
> > > this new one. Is there any better solution than that?
> > 
> > Disclaimer: if you tell anyone I told you this, I'll deny any knowledge
> > of the fact.
> 
> I've read about reinterpred_cast and I think the reason of your
> disclaimer is because the use of reinterpret_cast could be dangerous.
> What it's not clear to me is how and which cases reinterpret_cast
> could be dangerous. I suppose that in this case it's safe to use
> right?
> 
> >    QList<A *> list;
> >    QList<QObject *> objectList  *reinterpret_cast<QList<QObject
> > *>*>(&list);
> > 
> > The data structures in QList<T*> are isomorphic for all T.
> 
> What you mean with isomorphic? I understand that this concept is
> related to types with same structure or size but different ancestry.
> So, I deduced that casting two types with different size is the
> problem of using reinterpret_cast. Is it right?

I guess what he means is that pointers to anything (T) are always of the same 
"gestalt" at a binary level, e.g. the word-size of a void*.

So you can actually reinterpret_cast to QList<int *> if you wanted to, or 
whatever you like.

Of course things will go horribly wrong in the very moment you don't have a 
QObject behind that casted pointer.

Diez



More information about the Qt-interest-old mailing list