c++ - 子类 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
最终是否仍然负责解除分配?
解决方案
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()
笔记:
析构函数
~Derived()
甚至virtual
没有virtual
关键字,因为它的基类的析构函数Base
是。~Derived()
尽管通过删除指向基类的指针,首先调用析构函数Base
。(这就是虚拟析构函数的意图。)所有基类的析构函数也被调用(以及构造函数,但顺序相反)。
推荐阅读
- arrays - 在 C 代码中将 char 数组元素转换为等效的十六进制
- javascript - 剑道对话框弹出多次单击多次打开
- c# - Mongodb C# 试图读取流的末尾
- flutter - Dart:标识符之前与之后的感叹号
- python - 两个名称非常相似的列表的模糊匹配
- python - 如何找到元素之间的差异,忽略 NA 值
- python - Have gradient colours in sns.pairplot for one column of dataframe so that I can see which datapoints are connected to each other
- unity3d - 如何在具有特定 android 版本的 android 模拟器上测试 Unity 游戏?
- qt - 如何使用 yocto 构建简单的 qt 应用程序?
- linux - Xbindkeys 绑定鼠标按键来模拟 Super Key