gpt4 book ai didi

c++ - qt :all classes inherit from QObject or delete Manually after new? 我应该采取什么方式

转载 作者:太空宇宙 更新时间:2023-11-04 12:05:05 24 4
gpt4 key购买 nike

有一些问题让我很困惑:1.

QLabel *label = new QLabel(this);
//or
QLabel *label = new QLabel;
//if I forgot to set label as a child of other widget, it causing a memory leak?

2。

QList<MyClass> myList;
MyClass *my = new MyClass;
myList.append(*my);
//is necessary?
delete my;

那么,qt应该怎么走呢?所有类都继承自QObject还是新建后手动删除?或者使用Qt智能指针?请帮助我,非常非常感谢...

最佳答案

在 C++ 中如何分配对象取决于预期的生命周期,而 Qt 不会改变这一点。所以,是的,在情况 1 中,第二个标签被泄露,因为它的生命周期与 this 无关。

在 csae 2 中,您使用了不必要的堆分配。随便写

{
QList<MyClass> myList;
MyClass my; // Local scope
myList.append(my);
}

或者更简洁:

{
QList<MyClass> myList;
myList.append( MyClass() ); // Unnamed object, can be moved into myList.
}

关于c++ - qt :all classes inherit from QObject or delete Manually after new? 我应该采取什么方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12523631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com