Question

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?

Was it helpful?

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."

OTHER TIPS

As @Kunal mentioned, it's better to pass raw pointer in your case, but I see that you are experiencing pointer ownership problems. Passing raw pointers to object's methods is dangerous, because when your code base grows, you'll soon become confused about which object is the owner of that particular pointer and this can lead to memory leaks very easily. For that reason, I would recommend to use QSharedPointer instead of QPointer or even raw pointer. QSharedPointer supports polymorphism, so you will be able to pass it (as a value) to any function/object you would like, without worrying about ownership, because QSharedPointer will take ownership of the pointer and will delete it when all last instance of QSharedPointer goes out of scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top