QCustomPlot Discussion and Comments

delete QCPCurveReturn to overview

I have a question about delete object QCPCurve. I'm creating the pointer:

QCPCurve *newCurve = new QCPCurve(ui->customPlot->xAxis, ui->customPlot->yAxis);

but I don't know when it can be removed
Was an attempt to create the smart pointer
QSharedPointer

but when calling:
customPlot->removePlottable(customPlot->plottable());

program is crashing
Help me, please

i wouldnt use a QSharedPointer. QCustomPlot takes ownership of all plottables, so it would get deleted by the customplot.

I dont know how you are calling QCustomPlot::plottable without passing in an index though. I would definitely check to make sure that it isnt just passing 0 into the removePlottable function

According to the documentation calling QCustomPlot::plottable without passing an index deletes the last added QCPCurve

In my program, I create a lot of QCPCurve pointers and therefore I want to be sure that the pointers will be deleted.

Also, I noticed that after calling removePlottable the pointer value is not null. It worries me.

How do I check that pointers are actually being deleted?

From the documentation, the removePlottable method deletes the plottable and the related items (legend), deallocating the plottable and items memory. It does not destroy the pointer.
As you created the pointer you have to manage it and set its value to null if needed.

So, I must manage QCPCurve pointer. I'm confused. As stated above, qcustomplot is destroy the QCPCurve pointer. You just said that removePlottable method does not destroy the pointer. How then destroy the pointer?

QVector<double> x(101), y(101);
for (int i=0; i<101; ++i)
{
    x[i] = i/50.0 - 1;
    y[i] = x[i]*x[i];
}
customPlot->addGraph();
customPlot->xAxis->setLabel("x");
customPlot->yAxis->setLabel("y");
QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);
newCurve->setName("Test");
newCurve->setData(x, y);
customPlot->rescaleAxes();
customPlot->replot();
customPlot->removePlottable(customPlot->plottable());
delete newCurve;

this code crash the program!

Please, review this program.

Consider refreshing your knowledge about memory management with pointers, shared pointers, scope, and the concept of ownership in C++.

You have a local variable newCurve, which points to an object that is memory-managed by QCustomPlot (it "lives inside" QCP).
How would QCP (or any class that you pass ownership for that matter), access that local pointer variable of yours and set it to nullptr?

The simple solution: Do not delete newCurve. You are by contract of ownership not allowed to do that.

Otherwise: use QPointer to track ownership (read its documentation in Qt!). QPointer is special in that it uses the QObject system to detect of the object was destroyed somewhere else in the code (like in removePlottable), and then sets itself to nullptr.