I just have a general question here. Is it a good idea to use a QSharedPointer or a QScopedPointer to handle widgets? For example:
I have been trying to make this work properly within a psuedo widget factory i have made( as the application has thousands of widgets) and I want to make sure that the memory is de-allocated properly. But everytime i try to implement this i recieve a seg fault. here is a code snippet.
- /// I am not sure if this line is valid
- return ButtonFactory::button.data();
but simply using QSharedPointer OR QScopedPointer in this manner seg faults it and I am not sure if it is due to the manner in which i am calling the function later ( located in another class that builds widgets into a frame with a layout).
It is a good idea to use QScopedPointer for exception safety and QSharedPointer for resource management. However, it is not recommended for QWidget derived classes (or QObject classes to a lesser degree). QWidgets are owned by their parent, and since they are reparented when put into layout, they can’t be used in a QSharedPointer unless they are never parented (or the parent is never destroyed while they are a child).
ButtonFactory::button seems to be a member of your class. As soon as you call your method a second time, you assign a new pointer to this variable, the reference count of the old one will go to 0 and your first button is deleted. This could be a cause for your segfault.
The API docs mentions this:
QSharedPointer:: operator= [doc.qt.nokia.com]
Makes this object share other’s pointer. The current pointer reference is discarded and, if it was the last, the pointer will be deleted.
QScopedPointer is even worse:
The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction. […] QScopedPointer guarantees that the object pointed to will get deleted when the current scope disappears.
So, as soon as you exit from your method, the just now created tool button is destroyed and the calling method receives an invalid pointer.
As Bradley already mentioned, as long as you give your QWidgets and QObjects a proper parent, Qt takes care of deleting all the stuff for you and theres hardly any need to worry for this.
It’s the other way round, that can do you some harm. If you destroy the objects yourself and if you set the parents correctly, it can happen, that your objects will be destroyed twice, which will lead to segfaults. Even the Trolls stepped into this trap in their official docs (see the Getting started example is buggy [developer.qt.nokia.com] thread), although in a slightly different way.