Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

"Avoid unnamed objects ..." warning when using QDomNode::appendChild



  • Using Qt 5.12.4, quite recently we switched from Visual Studio 2015 to Visual Studio 2019. Using Visual Studio 2019, the lines

    QDomDocument doc;
    const auto fooElement = doc.createElement("Foo");
    doc.appendChild(fooElement);
    

    result in the warning

    C26444 Avoid unnamed objects with custom construction and destruction (es.84).
    

    Looking at the documentation at https://doc.qt.io/qt-5/qdomnode.html#appendChild I see that appendChild returns a new reference to fooElement on success or a null node on failure. Does that mean I could do something like the following to make the warning go away?

    QDomDocument doc;
    auto fooElement = doc.createElement("Foo");
    fooElement = doc.appendChild(fooElement).toElement();
    if (fooElement.isNull()) {
        // handle error case
    }
    // do stuff with fooElement
    

    or am I misunderstanding things here?


  • Lifetime Qt Champion

    @Bart_Vandewoestyne said in "Avoid unnamed objects ..." warning when using QDomNode::appendChild:

    Does that mean I could do something like the following to make the warning go away?

    Did you try?

    https://docs.microsoft.com/en-us/visualstudio/code-quality/c26444?view=vs-2019



  • Yes, I did, and the warning goes away. I was just wondering if

    doc.appendChild(fooElement)
    // do stuff with fooElement
    

    was going to do the same as

    fooElement = doc.appendChild(fooElement).toElement();
    // do stuff with fooElement
    

    Using VS2019, I checked the value of fooElement's impl pointer, and the value before and after the call to

    fooElement = doc.appendChild(fooElement).toElement();
    

    was the same. So to be really on the safe side, I would say that

    QDomDocument doc;
    auto fooElement = doc.createElement("Foo");
    fooElement = doc.appendChild(fooElement).toElement();
    if (fooElement.isNull())
    {
        // handle error
    }
    // do stuff with fooElement
    

    is the safest way to append the child. However, I often simply see

    QDomDocument doc;
    const auto fooElement = doc.createElement("Foo");
    doc.appendChild(fooElement);
    

    from which I would think that most often, people simply do not check for appendChild errors.

    Any comments on this? Am I overlooking something? Could C++17's [[maybe_unused]] attribute come in handy here? Feel free to share thoughts.


Log in to reply