使用';新';在Qt中声明变量而不使用delete
从中,我可以得出结论,在Qt中声明新小部件有两种主要方式(当然,可能还有其他方式):使用';新';在Qt中声明变量而不使用delete,qt,memory-management,memory-leaks,new-operator,delete-operator,Qt,Memory Management,Memory Leaks,New Operator,Delete Operator,从中,我可以得出结论,在Qt中声明新小部件有两种主要方式(当然,可能还有其他方式): 不使用new关键字: 使用new关键字: 因此,在我的一些教程中,我看到讲师使用了第二种方法,之后没有使用delete。从我从很多文章(例如)中读到的内容来看,当使用new时,我们必须始终使用delete,以避免内存泄漏 但在阅读其他文章时,例如,他们提到: 只有在程序终止后,操作系统才能 清理并“回收”所有泄漏的内存 在我的程序中,当我想完全蒸发桌上的东西时,有时我确实使用了delete: QFormLayo
new
关键字:new
关键字:delete
。从我从很多文章(例如)中读到的内容来看,当使用new
时,我们必须始终使用delete
,以避免内存泄漏
但在阅读其他文章时,例如,他们提到:
只有在程序终止后,操作系统才能
清理并“回收”所有泄漏的内存
在我的程序中,当我想完全蒸发桌上的东西时,有时我确实使用了delete
:
QFormLayout *destroyAffineForm = inputFieldAffineBox->findChild<QFormLayout*>("inputFieldFormBoxAffine", Qt::FindChildrenRecursively);
while (destroyAffineForm->count() > 0 && (child = destroyAffineForm->takeAt(0)) != nullptr)
{
delete child->widget(); // delete the widget
delete child; // delete the layout item
}
delete destroyAffineForm;
QFormLayout*destroyAffineForm=inputfieldfaffinebox->findChild(“inputFieldFormBoxAffine”,Qt::findchildren递归);
而(destroyAffineForm->count()>0&&(child=destroyAffineForm->takeAt(0))!=nullptr)
{
删除子->小部件();//删除小部件
删除子项;//删除布局项
}
删除仿射形式;
但是,通常有很多小部件从程序启动到结束(没有我在最后调用delete
),都保持在原位,例如QLabel
保存一些标题文本
所以。。。总而言之,这些变量(在整个过程中一直持续到应用程序关闭)会导致内存泄漏吗?我必须插入一堆delete
语句来释放它们,还是操作系统最终会处理它?(我知道这可能是一个重复的问题,但我在这里得到了很多不同的说法)
附言:关于我的机器的一些信息
- 在Windows 10上操作,64位
- Qt Creator 4.14.2
- Qt 5.15.2(MSVC 2019,64位)
QLabel *label1 = new QLabel; // <<- NEED TO DELETE
QLabel *label2 = new QLabel(some_parent_obj); // Will be deleted when some_parent_obj is deleted
QLabel*label1=新的QLabel;//你可能想链接到:@drescherjm好建议!这似乎是一个无关紧要的问题,但是,对于在QtCreator的.ui
文件中创建的小部件(不是由代码创建的),它们的父级已经设置好了,所以不需要做任何事情,反之亦然?(示例图:)我自己从未使用过,但我无法想象你需要删除QtCreator为你制作的那些对象。
QFormLayout *destroyAffineForm = inputFieldAffineBox->findChild<QFormLayout*>("inputFieldFormBoxAffine", Qt::FindChildrenRecursively);
while (destroyAffineForm->count() > 0 && (child = destroyAffineForm->takeAt(0)) != nullptr)
{
delete child->widget(); // delete the widget
delete child; // delete the layout item
}
delete destroyAffineForm;
QLabel *label1 = new QLabel; // <<- NEED TO DELETE
QLabel *label2 = new QLabel(some_parent_obj); // Will be deleted when some_parent_obj is deleted