Menu

Memory Managment Question

2007-09-13
2013-05-20
  • Brian Foddy

    Brian Foddy - 2007-09-13

    I'm a little unsure about some basic aspect of the API, namely using InsertEndChild vs LinkEndChild.  I see from the source, InsertEndChild clones the provided node with a new, and then attaches it to the parent.  This seems safer to me, but is the following also safe:

    method1 (TiXmlNode node)
    {

    }

    method2 ()
    {

     
    • Brian Foddy

      Brian Foddy - 2007-09-13

      Sorry, somehow posted the note before its done:
      what I was trying to describe:

      method1 (TiXmlNode & node)
      {
          TiXmlElement elem ("Foo");
          node.LinkEndChild (&elem);
      }

      method2 ()
      {
          TiXmlDocument doc;
          method1 (doc);
          //  continue to use the elem element created in method1
      }

      As I see it, elem was created on the stack, and LinkEndChild doesn't clone it, but rather just assign the pointer to the parent node.  Now it goes out of scope, hence the parent doc has a pointer to lala land.

      Am I following this right?  Hence, I would new each element created in a sub method.

       
    • Lee Thomason

      Lee Thomason - 2007-09-15

      Brian --

      You are correct. You should be using InsertEndChild(), not LinkEndChild(). InstertEndChild() does the copy and won't lose memory.

      LinkEndChild() is an optimization method , from the docs:

          /** Add a new node related to this. Adds a child past the LastChild.

              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.

              @sa InsertEndChild
          */

      lee

       

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.