gpt4 book ai didi

c++ - 需要手动删除 QValidator 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:14:39 26 4
gpt4 key购买 nike

示例代码:

QDoubleValidator *validator = new QDoubleValidator();
myInputLineEdit->setValidator(validator);

// delete validator;

注意:myInputLineEdit 是一个 QLineEdit 指针,将与其父级一起删除。

我的问题是,我什么时候应该删除验证器,因为它是手动创建的,而且根据文档,setValidator() 似乎没有取得此指针的所有权?如果不删除,会不会内存泄露?

我试图在之后立即删除它,就像注释代码一样,我注意到在那之后 myInputLineEdit 的验证器变成了 0。所以我想我可能需要在删除 myInputLineEdit 之后再删除它。

另一个想法是,我可以给验证器一个父节点,这样它就会连同它的父节点一起被删除,这是一个很好的方法吗?如果没有合适的家长候选人怎么办?

谢谢

最佳答案

I tried to delete it right after, like the commented code, and I noticed the validator of myInputLineEdit became 0 after that. So I think I may need to delete it after myInputLineEdit is deleted.

这是因为 QLineEdit 在内部使用了 QPointer,它跟踪 QValidator 对象是否被删除。

and setValidator() doesn't seem to take ownership of this pointer according to the documentation

setValidator() 确实没有设置 QValidator 的父级。

Another thought is, I could give validator a parent so it will be deleted along with its parrent, is this a good way to do that? What if there isn't a good candidator to be the parent?

您可以手动删除它,使用智能指针或像@crayzeewulf 说的那样 - 将 myInputLineEdit 设置为父级(使用 QValidator 构造函数或 setParent())。父级负责删除其子级,因此这是一种可行的方法。通常分配验证器的对象是一个好的父对象。

If I don't delete it, will it be a memory leak?

如果既不设置父对象也不删除它,将会发生内存泄漏。

关于c++ - 需要手动删除 QValidator 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28099713/

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