首页 > 解决方案 > 子类 QCPGraph 的正确分配和解除分配

问题描述

我正在使用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

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

QCPDrawableGraph* dgr = new QCPDrawableGraph(plot->xAxis,plot->yAxis); //?

的析构函数QCustomPlot最终是否仍然负责解除分配?

标签: c++qtinheritancememory-managementqcustomplot

解决方案


s 内存管理的一般概念QWidget是,如果子组件本身被删除,父组件会关心子组件的删除。

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

OP的情况QCPDrawableGraph也是如此。

它在文档中明确提到。(构造函数和析构函数文档QPCGraph

创建的QCPGraph会自动注册到从keyAxis推断的QCustomPlot实例。这个QCustomPlot实例拥有 QCPGraph 的所有权所以不要手动删除它,而是使用QCustomPlot::removePlottable()代替。

作为OP的构造函数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;
}

输出:

Derived::~Derived()
Base::~Base()

Live Demo on ideone

笔记:

  1. 析构函数~Derived()甚至virtual没有virtual关键字,因为它的基类的析构函数Base是。

  2. ~Derived()尽管通过删除指向基类的指针,首先调用析构函数Base。(这就是虚拟析构函数的意图。)

  3. 所有基类的析构函数也被调用(以及构造函数,但顺序相反)。


推荐阅读