Creating and deallocating a Qt widget object(创建和释放 Qt 小部件对象)
问题描述
听说widget应该在堆上分配(使用new),然后就不需要删除了(自动完成).
- 有人能解释一下原因吗?
- 如果小部件不是以这种方式分配而是在堆栈中,会发生什么情况?
我不确定这是否重要,但我创建的所有小部件都有一个父级.
这个说:
<块引用>如果 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).
- Can someone explain why?
- 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.
这篇关于创建和释放 Qt 小部件对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建和释放 Qt 小部件对象
基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
