c++qtpointersqpointer

QPointer containing derived object wont match one with the baseclass


Sorry about the wierd title, feel free to come up with a better one if you can think of one.

Here is my issue.

I have a structure that looks something like this:

QObject -> MyBase -> MyDerived

I then have a function that will take any of the derived types as a QPointer;

void function(QPointer<MyBase> base) {
   ...
}

The issue is now that I cannot pass QPointer<MyDerived> into this function, which I would if I used standard pointers. Do I have to cast this object to make it fit to the function? Or should I just use normal pointers?

Also, does anyone know the standard behavior when you allocate an object which fails? Should you always do this in a try-block or wrap it in something to check if it's null or not? I read the Qt documentation and they said that most of their classes returned a null value if it failed to allocate. When is that statement true and what can I do if I don't want to use try-catch?


Solution

  • you should use normal pointer. This is what Qt Document says about using QPoiner

    "A guarded pointer will automatically cast to a T *, so you can freely mix guarded and unguarded pointers. This means that if you have a QPointer<QWidget>, you can pass it to a function that requires a QWidget *. For this reason, it is of little value to declare functions to take a QPointer as a parameter; *just use normal pointers*. Use a QPointer when you are storing a pointer over time."