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.

Qt Code:
  1. auto e = myVariant.value<QSharedPointer<Entity>>();
To copy to clipboard, switch view to plain text mode 
returns null

Qt Code:
  1. auto ne = *reinterpret_cast<QSharedPointer<Entity>*>(myVariant.data());
To copy to clipboard, switch view to plain text mode 
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