[Qt-interest] QList<T> conversion
Guillaume CLEMENT
tortuxm at baobob.org
Tue Feb 1 17:36:24 CET 2011
Hello,
> Second, I only now realize that you actually asked to "downcast" (from A to its base class QObject) every item in the
> list, probably because you need to match the signature of some method, as in
>
> // A inherits from QObject
> QList items;
> QList objects = reinterpret_cast >(items);
> doFoo(objects);
>
> with
>
> void doFoo(QList objects) {...}
>
>I guess that is your use case, right?
>
>I don't see why "downcasting" should be dangerous, even though it generally hints at some "design issues".
Usually the problem is, what happens if the "doFoo" function adds an incompatible object to the list ? It can do so, since the list is a QList<QObject*>.
For example with this code :
QList<A*> *firstList = someList();
QList<QObject*> *secondList = reinterpret_cast<QList<QObject*> >(firstList);
secondList ->append(new B()); // Where B inherits QObject but not A
A *a = firstList->last(); // What happens ? My guess is that A will be invalid and reading / writing to it would be bad at this stage.
Some B was just added in firstList, although it is not a A. But firstList is a QList<A*>.
I don't think there are other issues though, so it might "just work" if the list is only used for reading (I didn't dig the source code of QList but my guess is that the QList of pointers should be compatible, since all pointers have same sizes and have the same behaviour)
Hope this helps,
- Guillaume
More information about the Qt-interest-old
mailing list