创建和释放 Qt 小部件对象

2021-12-09 00:00:00 qt memory-management c++

听说widget应该在堆上分配(使用new),然后就不需要删除了(自动完成).

  1. 有人能解释一下原因吗?
  2. 如果小部件不是以这种方式分配而是在堆栈中,会发生什么情况?

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

这个说:

<块引用>

如果 parent 为 0,则新小部件变为一个窗口.如果 parent 是另一个小部件,这个小部件成为一个子窗口内父.新的小部件是删除其父项时删除.

解决方案

没有魔法.简单地说,一个 QObject 会在它的析构函数中自动删除它的孩子.所以,只要你的小部件有一个父级并且你销毁了那个父级,你就不必担心子级.因此,如果您想知道 QObject * parent 参数是什么,那么,这就是它的用途.

此外,来自文档:

<块引用><块引用>

删除所有子对象.如果这些对象中的任何一个在堆栈上或全局上,您的程序迟早会崩溃.

因此,避免将父级分配给堆栈分配的对象.

I heard that the widgets should be allocated on the heap (using new), and then there are no needs to delete them (it is done automatically).

  1. Can someone explain why?
  2. What happens if a widget is not allocated that way, but on a stack?

I am not sure if it matters, but all widgets I am creating have a parent.

This says :

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.

解决方案

There's no magic involved. Simply put, a QObject automatically deletes its children in its destructor. So, as long as your widget has a parent and that you destroy that parent, you don't have to worry about the children. So if you wondered what was that QObject * parent parameter, well, that's what it's there for.

Also, from the doc:

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

So, avoid giving parents to objects that are stack-allocated.

相关文章