c++ - 创建和释放 Qt 小部件对象

标签 c++ qt memory-management

听说widgets应该分配在堆上(用new),然后就不用删除了(自动完成)。

  1. 谁能解释为什么?
  2. 如果小部件不是以这种方式分配,而是分配在堆栈上,会发生什么情况?

我不确定这是否重要,但我创建的所有小部件都有父级。

This说:

If parent is 0, the new widget becomes a window. If parent is another widget, this widget becomes a child window inside parent. The new widget is deleted when its parent is deleted.

最佳答案

没有魔法。简而言之,QObject 在其析构函数中自动删除其子对象。因此,只要您的小部件有父级并且您销毁了该父级,您就不必担心子级。因此,如果您想知道 QObject * parent 参数是什么,那么,这就是它的作用。

此外,来自文档:

All child objects are deleted. If any of these objects are on the stack or global, sooner or later your program will crash.

因此,避免为堆栈分配的对象提供父对象。

关于c++ - 创建和释放 Qt 小部件对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4267854/

相关文章:

c++ - 如何在 C++ 中使用回溯获取正确的代码行?

C++高性能文件读写(C++14)

c++ - 在 QTCreator 中使用 MinGW 编译 c++ 和 cuda 代码

c++ - 尝试使用 QQmlListProperty 时出现 Qt 编译器错误

c++ - 为大节点树动态分配内存

c++ - 新关键字 "auto";什么时候应该使用它来声明变量类型?

python - 使用 SWIG 在 Python 中包装 C++ 类

c++ - Qt Creator 中最有用(高效)的快捷方式

c++ - “placement new”有什么用?

c++ - PageHeap 不显示确切的崩溃位置