PDA

View Full Version : Get unknown class from QVariant



sedi
21st April 2017, 22:31
I have many classes that inherit a common base class Entity.
I have to iterate over many QVariants that each contain one object of one of those subclasses. I don't know the objects exact class, but Entity has a getClassname(), so that's fine. My problem is to safely get the subclass from the void* of QVariant::data() method.


auto e = myVariant.value<QSharedPointer<Entity>>();
returns null


auto ne = *reinterpret_cast<QSharedPointer<Entity>*>(myVariant.data());
works most of the time, but every now and then it doesn't - meaning that the object is broken (non-null!), crashing at once when using getClassname() or a bit later when using some other parts of the object.

As I understand, I just cannot assume that using reinterpret_cast is safe because the internal representation of my Objects in QVariant might sometimes be "non-trivial".

Is that correct?
Is there any possibility to safely get my objects from the variant?


Best regards,
Sebastian

wysota
21st April 2017, 22:55
QVariant stores a serialized copy of an object thus if the shared pointer gets invalidated I belive the stored instance might not be aware of it. I would be very hesitant to use a shared pointer with QVariant. The safest, foul proof approach I can suggest is to have a manager for Entity objects and store id of an object in QVariant so that when you read the value back, you can ask the manager for an object with the given id (if it exists).