XML crashes out of scope

Hello, I’m getting a exception when I create an XML element and leave scope
This is just an example I can’t make work, it doesn’t mean anything…
*NB it has no attributes, just child elements.

	ScopedPointer<XmlElement>  xml = new XmlElement("test");
	ScopedPointer<XmlElement> text1 = xml->createNewChildElement("name");
	ScopedPointer<XmlElement> text2 = xml->createNewChildElement("name2");

	text1->addTextElement(String("Fred Bloggs"));
	text2->addTextElement(String("Amy Bloggs"));

//..Save the xml file, since deleted to track down error...

} // .. Leave scope

If I don’t use pointers then it still crashes. If I simply just set text attribs to ‘xml’ then it quits fine.
The exception stops here on being called from delete object.

   inline operator ObjectType*() const noexcept
        return item; **X**
Exception thrown: read access violation.
**this** was 0xFFFFFFFFFFFFFFFF. occurred

You cannot take ownership (using a ScopedPointer) of the XmlElements created by createNewChildElement, as they are already owned by their parent XmlElement. In your example, at the end of the scope, text2 is deleted, then text1 is deleted, then xml is deleted and tries to delete its children XmlElement “again”.

Your example will work if you re-write it like this

    ScopedPointer<XmlElement> xml = new XmlElement("test");
    XmlElement* text1 = xml->createNewChildElement("name");
    XmlElement* text2 = xml->createNewChildElement("name2");

Oh, thanks!! Memory confusion, who owns what and all that. :slight_smile: