为什么官方Qt示例和教程不使用智能指针? [英] Why don't the official Qt examples and tutorials use smart pointers?

查看:386
本文介绍了为什么官方Qt示例和教程不使用智能指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么有关Qt库的官方示例和教程从不使用智能指针?我只看到 new delete 用于创建和销毁小部件。

Why do official examples and tutorials about the Qt library never make use of smart pointers? I only see new and delete for creating and destroying the widgets.

我搜索了基本原理,但找不到它,除非是出于历史原因或向后兼容,否则我自己也看不到:并非每个人都希望程序在小部件构造函数失败并处理时终止通过try / catch块很难看(即使在很少的地方使用)。父级小部件可能拥有孩子的所有权这一事实也只是部分地向我说明了这一点,因为在某些级别您仍必须对父级使用 delete

I searched for the rationale but I could not find it, and I don't see one myself except if it's for historic reasons or backward compatibility: not everyone wants the program to terminate if a widget constructor fails, and handling it via try/catch blocks is just ugly (even if used in few places). The fact the parent widgets may take the ownership of the children also only partially explains the thing to me, as you would still have to use delete for the parents at some level.

推荐答案

因为Qt依赖于父子模型来管理Qobject资源。它遵循复合+责任链模式,该模式用于从事件管理到内存管理,绘图,文件处理等。

Because Qt relies on a parent-child model to manage Qobject resources. It follows the composite + Chain-of-responsibility pattern, which is used from event management to memory management, drawing, file handling, etc...

实际上,在共享的唯一指针中使用QObject 工程过度(99%的时间)。

Actually, trying to use a QObject in a shared\unique pointer is overengineering (99% of the time).


  1. 您必须提供一个自定义删除器,该删除器将调用deleteLater

  2. 您与父母已建立的qobject父对象中的引用。因此,您知道只要父对象存在,对象就不会泄漏。当您需要摆脱它时,可以直接调用 deleteLater

  3. 没有父项的QWidget已具有引用。与第2点相同。

  1. You have to supply a custom deleter which will call deleteLater
  2. Your qobject with parents already have a reference in the parent object. So you know that a object is not leaked as long as the parent exist. When you need to get rid of it, you can call deleteLater directly.
  3. Your QWidget without parent already have a reference in the Qapplication object. So same as point 2.

也就是说,您仍然可以将RAII与Qt一起使用。例如, QPointer 充当 QObject 。我将使用 QPointer< QWidget> 而不是 QWidget *

That said, you can still use RAII with Qt. For instance QPointer behaves as a weak reference on a QObject. I would use QPointer<QWidget> rather than QWidget*.

注意:不要听起来太疯狂,两个词:Qt + valgrind。

note: to not sound too fanboy, two words : Qt + valgrind.

这篇关于为什么官方Qt示例和教程不使用智能指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆