1. 程式人生 > >QCustomPlot使用過程中出現的錯誤

QCustomPlot使用過程中出現的錯誤

我們知道在使用一個類的指標時,應先在標頭檔案中宣告,在建構函式中初始化或者new出來,一定不能不初始化,否則會出現記憶體錯誤。在解構函式中還應該把該指標delete掉,並且讓其為NULL。

if(p != NULL)
{
delete p;
p = NULL;
}

然而我的專案在想用QCumstomPlot畫圓時,使用了QCumstomPlot的QCPCurve類。主要程式碼如下:

宣告:

QCPCurve *rotaryErrCurve;

建立:

rotaryErrCurve = new QCPCurve(ui->rotaryErrWidget->xAxis, ui->rotaryErrWidget->yAxis);

其他設定以及使用就不多贅述。在解構函式中:

if(rotaryErrCurve != NULL){
        delete rotaryErrCurve;
        rotaryErrCurve = NULL;
}

將這些部分新增到我原有工程裡之後,老是出現錯誤:

C:\Program Files (x86)\SogouInput\Components\Error - RtlWerpReportException failed with status code :-1073741823. Will try to launch the process directly

程式異常結束。

G:\luoyong\51daq\build-51daq-Desktop_Qt_5_6_3_MinGW_32bit-Release\release\51daq.exe crashed.

我們知道這就是訪問不存在或者不正確的地址造成的。在已知其他部分功能正常的情況下,復返檢查新加部分也沒有發現錯誤。直至在開啟QCusomPlot的HELP檔案,看到QCPCurve的建構函式的說明部分如下:

QCPCurve::QCPCurve (QCPAxis * keyAxis,explicit QCPAxis * valueAxis )
Constructs a curve which uses keyAxis as its key axis ("x") and valueAxis as its value axis ("y"). 
keyAxis and valueAxis must reside in the same QCustomPlot instance and not have the same orientation. 
If either of these restrictions is violated, a corresponding message is printed to the debug output (qDebug), the construction is not aborted, though.
The created QCPCurve is automatically registered with the QCustomPlot instance inferred from keyAxis. 
This QCustomPlot instance takes ownership of the QCPCurve, so do not delete it manually but use QCustomPlot::removePlottable() instead. 

前面部分都挺正常的,看到最後一句話我坐不住了。。。

do not delete it manually but use QCustomPlot::removePlottable() instead. 

然後我把delete部分改為:

    if(rotaryErrCurve != NULL)
    {
        ui->rotaryErrWidget->removePlottable(0);
        rotaryErrCurve = NULL;
    }

就好了。。。。

教訓:

在使用一個不熟悉的類時要仔細閱讀它的說明文件,不要想當然。