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?
Qt Code:
  1. void MainWindow::on_pushButton_clicked()
  2. {
  3. ui->stackedWidget->setCurrentIndex(1);
  4. QwtPlot *plotWidget = findChild<QwtPlot *>("plotWidget");
  5. curve = new QwtPlotCurve(); //curve is class member declared in header
  6. qDebug() << "Curve created, its address:" << curve;
  7. curve->setPen(Qt::blue);
  8. int y;
  9. QVector<double> xData, yData; //vectors to plot curve data
  10. for (int i=-100; i<=100; i++)
  11. {
  12. y=i*qSin(i);
  13. xData.append(i); //fill vectors
  14. yData.append(y); //fill vectors
  15. }
  16. int size = xData.size();
  17. curve->setSamples(xData.data(), yData.data(), size);
  18. curve->attach(plotWidget);
  19. plotWidget->setAxisAutoScale(QwtPlot::xBottom);
  20. plotWidget->setAxisAutoScale(QwtPlot::yLeft);
  21. Replot to update the plot with the curve
  22. plotWidget->replot();
  23. }
  24. void MainWindow::on_pushButton_2_clicked()
  25. {
  26. ui->stackedWidget->setCurrentIndex(0);
  27. ui->plotWidget->detachItems(QwtPlotItem::Rtti_PlotCurve, true);
  28. //delete curve; ------ this line crashes my app if uncommented
  29. curve = nullptr;
  30. if(curve==nullptr)
  31. { qDebug()<<"curve is nullptr";}
  32. }
To copy to clipboard, switch view to plain text mode