Qt 对象的生命周期
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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.
使用
new
分配的对象必须使用delete
释放。然而,对于 Qt,大多数对象都可以有一个父对象,您可以将其指定为构造函数的参数。当父对象被删除时,子对象也会自动删除。
Objects allocated with
new
must be released withdelete
.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.
如果您出于某种原因不想传递父级(因为没有 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.