在下面的 C++ 代码中,使用 QQmlIncubator
创建了一个 QML 组件。 Qt 文档从这里有这个片段 http://doc.qt.io/qt-5/qqmlincubator.html :
QQmlIncubator incubator;
component->create(incubator);
while (!incubator.isReady()) {
QCoreApplication::processEvents(QEventLoop::AllEvents, 50);
}
// Who owns 'object'? When is it deleted?
QObject *object = incubator.object();
据我了解,此代码段并不完整,因为您需要在组件上调用 delete
。根据http://doc.qt.io/qt-5/qqmlcomponent.html#create , QQmlComponent::create()
函数将返回的对象实例的所有权转移给调用者。到目前为止还不错。
现在我的问题来了——谁拥有上面代码片段中的 object
?在我的例子中,我将上面的代码片段放在一个类的成员函数中,所以 QQmlIncubator incubator
超出了范围,我只保留 component
和object
,它们都是它们包含类的实例变量,我在析构函数中调用了delete component
。我清理得当吗?
那么object
是否属于component
呢? object
什么时候被销毁?
更新1
请参阅我的后续问题:Safely deleting QML component being used in StackView transition .
最佳答案
简答
您应该销毁孵化对象(如果孵化器成功完成),否则会发生内存泄漏。
如何管理所有权?
一个好的方法可能是将所有权转移到 object parent使用 QObject::setParent
,例如 visual parent .这也是done by Qt when you construct QML objects in the traditional way :
Any object assigned to an item's data property becomes a child of the item within its QObject hierarchy, for memory management purposes.
For convenience, the Item data property is its default property.
推理
如 QQmlComponent::create(QQmlContext *)
中所述文档,对象所有权转移给用户:
The ownership of the returned object instance is transferred to the caller.
因此,重载函数 QQmlComponent::create(QQmlIncubator &incubator, QQmlContext *context, QQmlContext *forContext)
不太可能将保留所有权,尽管文档中未明确提及。有人可能会争辩说所有权已转移给 QQmlIncubator
目的。只要组件正在 Loading
中,情况确实如此,一旦准备就绪,所有权就会被释放(隐式地)记录在 QQmlIncubator::clear
中。 :
Any in-progress incubation is aborted. If the incubator is in the Ready state, the created object is not deleted.
请注意,QQmlIncubator::clear
是在 QQmlIncubator
的析构函数中调用的。
关于c++ - 谁拥有 QQmlIncubator 返回的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43811345/