Qt 对象的生命周期

发布于 2024-09-10 04:22:49 字数 260 浏览 2 评论 0原文

Qt 对象的生命周期是多少?

如:

QTcpSocket *socket=new QTcpSocket();

socket什么时候会被销毁?我应该使用

delete socket;

是否有任何区别:

QTcpSocket socket;

我找不到有关此的深层信息,欢迎任何评论或链接。

What are the lifetimes of Qt Objects?

Such as:

QTcpSocket *socket=new QTcpSocket();

When socket will be destroyed? Should I use

delete socket;

Is there any difference with:

QTcpSocket socket;

I couldn't find deep infromation about this, any comment or link is welcomed.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

醉殇 2024-09-17 04:22:49

Qt 使用父子关系来管理内存。如果您在创建 QTcpSocket 对象时为其提供父对象,则父对象将负责清理它。例如,父窗口可以是使用套接字的 GUI 窗口。一旦窗口消失(即关闭),套接字就会消失。

您可以不使用父对象,但实际上您必须手动删除该对象。

我个人建议坚持使用惯用的 Qt 并使用将所有对象链接到父子树中。

Qt uses parent-child relationships to manage memory. If you provide the QTcpSocket object with a parent when you create it, the parent will take care of cleaning it up. The parent can be, for example, the GUI window that uses the socket. Once the window dies (i.e. is closed) the socket dies.

You can do without the parent but then indeed you have to delete the object manually.

Personally I recommend sticking to idiomatic Qt and using linking all objects into parent-child trees.

一张白纸 2024-09-17 04:22:49

使用new分配的对象必须使用delete释放。

然而,对于 Qt,大多数对象都可以有一个父对象,您可以将其指定为构造函数的参数。当父对象被删除时,子对象也会自动删除。

Objects allocated with new must be released with delete.

However, with Qt, most objects can have a parent, which you specify as an argument to the constructor. When the parent is deleted, the child objects get deleted automatically.

红尘作伴 2024-09-17 04:22:49

如果您出于某种原因不想传递父级(因为没有 QObject 可以拥有套接字对象),您还可以使用 QSharedPointer 来管理生命周期。

If you don't want to pass a parent for some reason (because there is no QObject where it makes sense to own the socket object), you can also use a QSharedPointer to manage the lifetime.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文