Qwt proper pointer management
Dear community, I have started to learn cpp just a few month ago and thanks to other threads of forum, I become more familiar with Qt and Qwt as well. I want to ask you how to manage Qwt`s pointers properly to avoid memory leaks.
Consider a snippet of code where I try manually to delete my QwtPlotCurve* pointer that makes my app crash. This might happen due to attempt of double delete because the statement “detachItems(QwtPlotItem::Rtti_PlotCurve, true)” has already deleted it. I just want to ensure that using it is valid way to avoid memory leaks. Does this statement also delete curve-associated pointers like QwtPlotMarker*, QwtText*, etc if they would exist or I need to watch them myself? Just set pointer to nullptr is enough here to dangling pointer?
Code:
void MainWindow::on_pushButton_clicked()
{
ui->stackedWidget->setCurrentIndex(1);
QwtPlot *plotWidget
= findChild<QwtPlot
*>
("plotWidget");
curve
= new QwtPlotCurve();
//curve is class member declared in header qDebug() << "Curve created, its address:" << curve;
curve->setPen(Qt::blue);
int y;
QVector<double> xData, yData; //vectors to plot curve data
for (int i=-100; i<=100; i++)
{
y=i*qSin(i);
xData.append(i); //fill vectors
yData.append(y); //fill vectors
}
int size = xData.size();
curve->setSamples(xData.data(), yData.data(), size);
curve->attach(plotWidget);
plotWidget
->setAxisAutoScale
(QwtPlot::xBottom);
plotWidget
->setAxisAutoScale
(QwtPlot::yLeft);
Replot to update the plot with the curve
plotWidget->replot();
}
void MainWindow::on_pushButton_2_clicked()
{
ui->stackedWidget->setCurrentIndex(0);
ui
->plotWidget
->detachItems
(QwtPlotItem::Rtti_PlotCurve,
true);
//delete curve; ------ this line crashes my app if uncommented
curve = nullptr;
if(curve==nullptr)
{ qDebug()<<"curve is nullptr";}
}
Re: Qwt proper pointer management
If "curve" is derived from QObject, then it is owned by a parent QObject. When you are inside a slot, this ownership is not usually cleaned up until after the slot exits and control returns to the Qt event loop. So when you "delete" a QObject, your code can crash because the parent QObject still thinks it has control of the pointer. Do something like this:
Code:
curve->deleteLater();
curve = nullptr;
And be sure to check the value of curve elsewhere in your code to make sure you aren't trying to use a null pointer. deleteLater() tells Qt to delete the object after it has returned control to the event loop, not immediately the way "delete" does.