views:

509

answers:

2

I'm doing the following with TinyXml:

TiXmlDocument doc;
TiXmlDeclaration* decl = new TiXmlDeclaration( "1.0", "", "" );
TiXmlElement* main = new TiXmlElement("main");

TiXmlElement* header = new TiXmlElement("header");
header->SetAttribute("attribute","somevalue");
main->LinkEndChild(header);

// ... Add many more TiXmlElment* to other elements all within "main" element

doc.LinkEndChild(decl);
doc.LinkEndChild(main);

// ... do stuff with doc

// Now I am done with my doc. What memory management happens here?

At the end of my program's execution, will all of the TiXmlElement* be cleaned up when the doc goes out of scope? Do I need to walk the doc tree and free up all of the memory myself?

A: 

Anything you allocate with new will never be automatically cleaned up -- you (or at least, someone) needs to call delete header; etc.

I say "someone" because it's possible that the TiXmlDocument object takes ownership of these objects and cleans them up itself -- the only way to know that is to check TinyXML's documentation.

If it doesn't take ownership, you're better off just declaring local objects on the stack:

TiXmlDeclaration decl( "1.0", "", "" );    // etc.

If you need the objects to persist past the end of the function, it's safer to use shared pointers, e.g. Boost's shared_ptr.

j_random_hacker
This answer doesn't really do anything except bring up the points that prompted the question in the first place: Will the TiXmlElement objects get freed when doc goes out of scope, or does the developer need to free them manually?
Rob Kennedy
@Rob: I was trying to make the OP aware of the *concept* of ownership. If he is already aware of it, there are only two cases: either the TinyXML documentation does not describe it's ownership semantics, in which case I'd consider it too flaky to use; or it does, but the OP is too lazy to look it up.
j_random_hacker
+5  A: 

The documentation for LinkEndChild says this:

NOTE: the node to be added is passed by pointer, and will be henceforth owned (and deleted) by tinyXml. This method is efficient and avoids an extra copy, but should be used with care as it uses a different memory model than the other insert functions.

Rob Kennedy
So based on this he does not need to delete anything as all the objects are owned by doc?
Martin York
Not only does he not need to, he MUST not.
Rob Kennedy
+1, this is the answer the OP was looking for. But IMHO it was a bit lazy of him to make you read the documentation for him.
j_random_hacker