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 小部件对象
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
