TOC PREV NEXT INDEX


Dynamic Memory Management


In the case of C++, dynamic memory management is handled by the new and delete operators. In most cases, handling memory involves the common action of making sure to delete any pointer that was allocated with new when done with it. However, the generated C++ classes contain the concept of memory ownership which makes it possible for a user to assign ownership of memory to the container object being populated. This makes freeing the memory much easier. Instead of having to track each individual item, the class does it for you. Therefore, when the main container class is deleted at the end of use, all memory objects within that class that have had ownership assigned to the container are deleted as well.
In cases where memory ownership can be assigned to the container class, the class may contain assignment methods that contain a boolean ownMemory argument. If this argument is set to true, the class will assume the object being transferred has been allocated dynamically using the new operator and will invoke delete on the object from within its destructor. An example of a method with an ownMemory argument is the append method generated for a repeating element class (this is taken from the cpp/sample/simpleArray sample program):

class SimpleArray : public OSBaseType {
 
public:
 
   /* List of OSXMLStringClass */
 
   class item_list : public OSRTDListClass {
 
    public:
 
      void append (const OSXMLStringClass* pdata) {
 
         OSRTDListClass::append ((const void*)pdata);
 
      }
 
      void append (OSXMLStringClass* pdata, OSBOOL ownMemory=FALSE) {
 
         OSRTDListClass::append ((void*)pdata, ownMemory);
 
      }
 
      const OSXMLStringClass* getItem (int idx) {
 
		return (const OSXMLStringClass*) 
 
			OSRTDListClass::getItem (idx);
 
      }
 
   } item;
 
   ...
 

In this case, the item list is a list of strings. By using the second form of the append method to add an item to this list, memory ownership can be transferred to the list container. Then when the list is deleted, all of the objects with transferred ownership will be deleted as well.
There is also a setOwnMemory method defined in the OSBaseType base class. This method can also be used to transfer ownership of dynamic memory to the container class.
When an XML instance is decoded, the decoder automatically transfers memory ownership to the container objects. It is therefore not necessary for the user to worry about freeing memory for any of the items within a returned class instance. Deleting the object is all that is necessary to free the memory of all of the items within.

Objective Systems, Inc.

102 Pickering Way, Suite #506
Exton, Pennsylvania 19341
http://www.obj-sys.com
Phone: (484) 875-9841
Toll-free: (877) 307-6855 (US only)
Fax: (484) 875-9830
info@obj-sys.com
TOC PREV NEXT INDEX