5

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?

Alex B
  • 24,678
  • 14
  • 64
  • 87
  • 4
    What does the TinyXML documentation say? If it doesn't clearly explain its ownership semantics, I suggest not using it. –  May 12 '09 at 16:22

2 Answers2

13

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
  • 161,384
  • 21
  • 275
  • 467
-1

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
  • 50,331
  • 10
  • 105
  • 169
  • 4
    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 May 12 '09 at 16:35
  • 1
    @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 May 12 '09 at 20:56