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;
    }

就好了。。。。

教訓:

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章