XmlElement and pointers


#1
String NEQ::saveState()
{
    XmlElement xml ("AppState");
    XmlElement * x2 = new XmlElement("ChildElement");
    xml.addChildElement(x2);

    return xml.createDocument (String(), false, false);
}

Just a quick one. Will x2 leak or does it get owned by parent XML element. In the past I have just built XML in string builder (and parsed with XmlElement) but my new project is rather large and has a lot of nested elements ergo want to make sure that this works fine before adopting.


#2
void XmlElement::addChildElement (XmlElement* const newNode) noexcept
{
    if (newNode != nullptr)
    {
        // The element being added must not be a child of another node!
        jassert (newNode->nextListItem == nullptr);

        firstChildElement.append (newNode);
    }
}
//........

This is the backbone of the XmlElement class.

LinkedListPointer<XmlElement> firstChildElement;

Check out the usage example for LinkedListPointer:

    struct MyObject
    {
        int x, y, z;
        // A linkable object must contain a member with this name and type, which must be
        // accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
        // you could make your class a friend of a LinkedListPointer<MyObject> instead).
        LinkedListPointer<MyObject> nextListItem;
    };
    LinkedListPointer<MyObject> myList;
    myList.append (new MyObject());
    myList.append (new MyObject());
    int numItems = myList.size(); // returns 2
    MyObject* lastInList = myList.getLast();

and the destructor for the XmlElement:

XmlElement::~XmlElement() noexcept
{
    firstChildElement.deleteAll();
    attributes.deleteAll();
}

and the deleteAll() call:

    /** Iterates the list, calling the delete operator on all of its elements and
        leaving this pointer empty.
    */
    void LinkedListPointer::deleteAll()
    {
        while (item != nullptr)
        {
            auto oldItem = item;
            item = oldItem->nextListItem;
            delete oldItem;
        }
    }

#3

So it is safe then as it’s deconstr calls delete to each reference when my parent element goes out of scope. Cheers!