Qt中的内存管理? [英] Memory management in Qt?

查看:121
本文介绍了Qt中的内存管理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Qt很新,我想知道一些基本的内存管理和对象的生活。什么时候需要删除和/或销毁我的对象?是否自动处理这些?

I'm quite new to Qt and am wondering on some basic stuff with memory management and the life of objects. When do I need to delete and/or destroy my objects? Is any of this handled automatically?

在下面的示例中,我创建的哪些对象需要删除?当 myClass 被销毁时,实例变量 myOtherClass 会发生什么?如果我不删除(或销毁)我的对象会发生什么?这将是内存的问题吗?

In the example below, which of the objects I create do I need to delete? What happens to the instance variable myOtherClass when myClass is destroyed? What happens if I don't delete (or destroy) my objects at all? Will that be a problem to memory?

class MyClass
{

public:
    MyClass();
    ~MyClass();
    MyOtherClass *myOtherClass;
};



MyClass.cpp



MyClass.cpp

MyClass::MyClass() {
    myOtherClass = new MyOtherClass();

    MyOtherClass myOtherClass2;

    QString myString = "Hello";
}

正如你可以看到,这是一个相当新手容易的东西,

As you can see this is quite newbie-easy stuff but where can I learn about this in an easy way?

推荐答案

如果你使用 QObject 构建自己的层次结构$ c> s,也就是说,您用父级

If you build your own hierarchy with QObjects, that is, you initialise all newly created QObjects with a parent,

QObject* parent = new QObject();
QObject* child = new QObject(parent);

那么就足以 delete code> parent ,因为 parent 的析构函数会处理破坏。 (它通过发出信号这样做,所以即使您在父项之前手动删除 child 也是安全的。)

then it is enough to delete the parent, because the parents destructor will take care of destroying child. (It does this by issuing signals, so it is safe even when you delete child manually before the parent.)

你也可以先删除孩子,顺序无所谓。有关订单 的示例,请参阅有关对象树的文档

You could also delete the child first, the order doesn't matter. For an example where the order does matter here's the documentation about object trees.

如果 MyClass 不是 QObject

另外,请注意 QObject 的父子层次结构c $ c> s通常独立于C ++类层次结构/继承树的层次结构。也就是说,指定的子项不必是其父项的直接子类。

Also, note that the parent–child hierarchy of QObjects is generally independent of the hierarchy of the C++ class hierarchy/inheritance tree. That means, that an assigned child does not need to be a direct subclass of it’s parent. Any (subclass of) QObject will suffice.

由于其他原因,构造函数可能会有一些约束,因为然而;例如 QWidget(QWidget * parent = 0),其中父项必须是另一个 QWidget 可见性标志,因为你会这样做一些基本的布局;但对于Qt的一般层次系统,你允许任何 QObject 作为父类。

There might be some constraints imposed by the constructors for other reasons, however; such as in QWidget(QWidget* parent=0), where the parent must be another QWidget, due to e.g. visibility flags and because you’d do some basic layout that way; but for Qt's hierarchy system in general, you are allowed to have any QObject as a parent.

这篇关于Qt中的内存管理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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