正确分配和释放子类QCPGraph

问题描述 投票:2回答:1

我正在使用qazxsw poi并且有子类qazxsw poi以提供可绘制的图形。

QCustomPlot

通常,人们会创建新的图表

QCPGraph

我会像我一样使用自己的课程吗?

class QCPDrawableGraph : public QCPGraph {
    Q_OBJECT
public:
    QCPDrawableGraph(QCPAxis* x, QCPAxis* y) : QCPGraph(x,y) {
        //do stuff
    }
    virtual ~QCPDrawabelGraph() {} // necessary?
    //class stuff
};

QCustomPlot plot(parent); //where parent is the parent widget of the gui QCPGraph* gr = plot->addGraph(); // in case of QCPGraphs or QCPGraph* gr = new QCPGraph(plot->xAxis,plot->yAxis); // as with all other QCPAbstractPlottables 的析构函数最终是否仍在处理de-allocation?

c++ qt inheritance memory-management qcustomplot
1个回答
1
投票

QCPDrawableGraph* dgr = new QCPDrawableGraph(plot->xAxis,plot->yAxis); //? s内存管理的一般概念是父窗口小部件关心删除子项本身是否被删除。

如果在构造函数中给出父元素(几乎每个小部件构造函数都提供父指针)或者将子元素添加到父元组件,则QCustomPlot将成为另一个的子元素。

这也是OP的QWidget的情况。

它在文档中明确提到。 QWidgetQCPDrawableGraph):

创建的QPCGraph会自动注册到keyAxis推断的Constructor & Destructor Documentation实例。这个QCPGraph实例取得了QCustomPlot的所有权,所以不要手动删除它,而是使用QCustomPlot代替。

作为OP的QCPGraph的构造

QCustomPlot::removePlottable()

调用基础构造函数应该正确继承此行为。


关于破坏一点样本:

QCPDrawableGraph

输出:

QCPDrawableGraph(QCPAxis* x, QCPAxis* y) : QCPGraph(x,y) {
    //do stuff
}

#include <iostream> struct Base { virtual ~Base() { std::cout << "Base::~Base()\n"; } }; struct Derived: Base { ~Derived() { std::cout << "Derived::~Derived()\n"; } }; int main() { Base *p = new Derived(); delete p; return 0; }

笔记:

  1. 即使没有Derived::~Derived() Base::~Base() 关键字,析构函数Live Demo on ideone也是~Derived(),因为它的基类virtual的析构函数是。
  2. 首先通过删除指向基类virtual的指针来调用析构函数Base。 (这是虚拟析构函数的意图。)
  3. 所有基类的析构函数也被调用(以及构造函数,但顺序相反)。
© www.soinside.com 2019 - 2024. All rights reserved.