gpt4 book ai didi

c++ - 如何知道 Qt 表单是否有效

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:48 24 4
gpt4 key购买 nike

我目前有一个从 QMainWindow 派生的名为“foo”的 Qt 窗体类。

现在在其他类(class)我有这样的东西

class someclass
{
private:
foo* form;
......
public:
someclass()
{
form = NULL;
}
};

现在某个类中有一个方法需要知道 foo* 是否有效,如果它指向到有效的 foo 形式。我想知道实现这一目标的最佳方式是什么。我应该和

if(form!=NULL) {...}

问题是上述方法不能保证可靠有效的形式。有什么建议吗?

最佳答案

我认为您正在寻找智能指针。通常,这种检查是由弱指针完成的。这不会持有该对象的所有权,但它可以使用 isNull() method 检查有效性。 .

Qt为此建立了一个方便的类,叫做QWeakPointer .它通常与共享指针成对使用,即 QSharedPointer。在 Qt 世界中。

The QWeakPointer class holds a weak reference to a shared pointer

The QWeakPointer is an automatic weak reference to a pointer in C++. It cannot be used to dereference the pointer directly, but it can be used to verify if the pointer has been deleted or not in another context.

QWeakPointer objects can only be created by assignment from a QSharedPointer.

这里是您实际可以用来查看拥有该对象的主要 QSharedPointer 是否已删除引用指针的方法。

bool QWeakPointer::isNull() const

Returns true if this object is holding a reference to a null pointer.

Note that, due to the nature of weak references, the pointer that QWeakPointer references can become null at any moment, so the value returned from this function can change from false to true from one call to the next.

这样,其他类就不需要获得对具有所有权的指针的引用,但根据您的具体用例,您可以在任何地方都使用 QSharedPointer。

关于c++ - 如何知道 Qt 表单是否有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21055116/

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