How to use QSGGeometryNode without causing memory leak and ensure proper cleanup

I use QSGGeometry, QSGVertexColorMaterialand a QSGGeometryNodeto draw something real time on my QQuickItemderived class, which is MyQuickItemhere.

Below is my method updatePaintNode, where the essence of the redraw logic lies.

QSGNode * MyQuickItem::updatePaintNode(QSGNode * oldNode, UpdatePaintNodeData * updatePaintNodeData) {

  if (!oldNode) {
    oldNode = new QSGNode;
  }

  oldNode->removeAllChildNodes();

  QSGGeometry * geometry = GetMyGeometry();
  QSGVertexColorMaterial * material = new QSGVertexColorMaterial;
  QSGGeometryNode * child_node = new QSGGeometryNode;

  child_node->setGeometry(geometry);
  child_node->setMaterial(material);
  child_node->setFlag(QSGNode::OwnsMaterial);
  oldNode->appendChildNode(child_node);

  return oldNode;
}

Question: The
above logic works great . No functionality issues at all. No performance issues. But I'm worried that I'm causing a memory leak . Take a look at the next two lines in the above method updatePaintNode, where I highlight raw pointers.

QSGVertexColorMaterial * material = new QSGVertexColorMaterial;
QSGGeometryNode * child_node = new QSGGeometryNode;

, . , , , updatePaintNode. .

:
, 2 material child_node ?
child_node->setFlag(QSGNode::OwnsMaterial), , QtSceneGraph ?

:
oldNode->removeAllChildNodes() , . , ?

PS:
: . , . material child_node , :

auto material = std::make_shared<QSGVertexColorMaterial>();
auto child_node = new std::make_shared<QSGGeometryNode>();

, material child_node .

+4
1

, . updatePaintNode.

oldnode child_node

oldnode, QQuickItem:: updatePaintNode() . QSGNode QSGNode:: OwnedByParent, .

QSGNode:: OwnsMaterial child_node material, , child_node .

: ?

- . . node/nodes. , , QQuickItem. node → markDirty (QSGNode:: DirtyMaterial). , node, (, , , fg - ).

QSGNode * MyQuickItem::updatePaintNode(QSGNode * oldNode, UpdatePaintNodeData * updatePaintNodeData) {

    QSGGeometryNode *node = static_cast<QSGGeometryNode *>(oldNode);
    if (!node) {
        node = new QSGGeometryNode;

        QSGVertexColorMaterial * material = new QSGVertexColorMaterial;
        node->setMaterial(material);
        node->setFlag(QSGNode::OwnsMaterial);
    }

    // if GetMyGeometry returns every time a new dynamically allocated object then you should
    // call node->setFlag(QSGNode::OwnsGeometry) to not leak memory here:
    QSGGeometry * geometry = GetMyGeometry(); 
    node->setGeometry(geometry);
    // No need to call node->markDirty(QSGNode::DirtyGeometry) because setGeometry is called.

    return node;
}
+3

Source: https://habr.com/ru/post/1686305/


All Articles