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?
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";}
}
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";}
}
To copy to clipboard, switch view to plain text mode
Bookmarks