PDA

View Full Version : Question about the undo framework example



nilot
9th February 2017, 09:29
Hello,

My question is about the undoframework http://doc.qt.io/qt-5/qtwidgets-tools-undoframework-example.html and http://doc.qt.io/qt-5/qtwidgets-tools-undoframework-commands-cpp.html

The AddCommand class has a destructor :


AddCommand::~AddCommand()
{
if (!myDiagramItem->scene())
delete myDiagramItem;
}

Let's say that the stored item, myDiagramItem, is inside a scene. The scene has the responsability to delete it. So I wonder how this destructor can work because if the destructor of the scene is called before the destructor of AddCommand the pointer myDiagramItem will be invalid, so the first line (if (!myDiagramItem->scene()) ) should lead to a crash. How can we be sure that it will not happened ?


Second question, it seems that diagramScene stored in MainWindow doesn't have any parent, so how the memory of diagramScene is released ?
(See : http://doc.qt.io/qt-5/qtwidgets-tools-undoframework-mainwindow-cpp.html)

Thank you very much for your help.

anda_skoa
10th February 2017, 08:30
How can we be sure that it will not happened ?

One of your options is to track the undo/redo state. I.e. if your command knows that it is in state after undo then it owns the pointer, if it is in the state after redo, then the scene owns the pointer.

Or you pass a pointer/reference of the command to the item and the item "notifies" the command when it is being deleted.



Second question, it seems that diagramScene stored in MainWindow doesn't have any parent, so how the memory of diagramScene is released ?

If you don't pass a parent, you need are in basic C++ land: you delete it yourself or store the raw pointer in a smart pointer that deletes its data on destruction.

Cheers,
_

nilot
10th February 2017, 09:06
Thank you, I agree with everything you said, I am just wondering why this isn't done in the example.