本文介绍了动态内存在QT中取消分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

QT编码中动态分配的指针如何被销毁,因为我们不为它们写一个特定的析构函数?

How does the dynamically allocated pointers in QT coding are destroyed because we don't write a specific destructor for them?

推荐答案

要扩展,Qt有两个对象管理方法:

To expand on Neox's answer, Qt has two methods for object management:


  1. QObject树结构

  2. 指针类

因为这些原因,两者并不完美。

And the two don't really mix very well for reasons which will become apparent.

可以是免费或有父母。当QObject有它的父集合(通过为QObject构造函数提供一个指向另一个QObject的指针,或通过调用 setParent()),父QObject成为子QObject,并确保它的任何孩子被销毁时,它是。还有几种方法可用于检查子/父关系。

QObjects can either be 'free' or have a parent. When a QObject has its parent set (either by providing the QObject constructor with a pointer to another QObject, or by calling setParent()) the parent QObject becomes the owner of the child QObject and will make sure any of its children are destroyed when it is. There are also several methods available to inspect child/parent relationships.

管理动态分配对象的单独方法是托管指针类,它解释得很好。总结:

A separate method of managing dynamically allocated objects are the managed pointer classes which this paper explains quite well. To summarise though:


  • 类存储了一个指向动态分配的对象的指针,并且在销毁时删除它,因此当您需要具有明确的所有权和生命周期的对象时,它是很好的。

  • 类持有对共享指针的强引用[和]将删除它所持有的指针,当它超出范围,只要没有其他QSharedPointer对象引用它,因此,当所有权不清楚切,但你想确保它不会丢失,成为内存泄漏。 可用于共享指针,但不会暗示任何所有权。

  • "The QScopedPointer class stores a pointer to a dynamically allocated object, and deletes it upon destruction" and is therefore good when you need objects which have clear and obvious ownership and lifetime.
  • "The QSharedPointer class holds a strong reference to a shared pointer [and] will delete the pointer it is holding when it goes out of scope, provided no other QSharedPointer objects are referencing it" and is therefore good when ownership is not as clear cut, but you want to make sure it doesn't get lost and become a memory leak. QWeakPointer can be used to share the pointer without implying any ownership.

正如你所看到的,一些有保护的指针类可以用于QObject树,但是你应该确保你在阅读和理解文档之前否则可能导致数据结构损坏。

As you can see, some of the guarded pointer classes can be used with a QObject tree, but you should make sure you read and understand the documentation thoroughly before doing so or you may end up with a corrupt data structure.

这篇关于动态内存在QT中取消分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 10:59