What memory management do I need to cleanup when using TinyXml for C++?

混江龙づ霸主 提交于 2019-12-19 19:17:22

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/853559/what-memory-management-do-i-need-to-cleanup-when-using-tinyxml-for-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!