When to Clone/Release Data Structures.

Part of MLDesigner's data structure mechansim are classes that handle the copying and releasing of data structure value objects. The base class is called TypeRef.

The TypeRef class is ancestor to some type specific classes. They are suffixed with a distinctive R. To avoid any problems that might appear (like memory leak or unexpected behavior) it is better to use only this kind of classes when programming using data structures.

The aforementioned mechanism is based on the object's lifetime. Every time a reference object is created it increases the reference counter of the value object. When the object is destroyed the reference counter is decreased. When the counter becomes zero the value data structure is put into a pool of free elements. As a result the lifetime of those objects must not exceed the scope of the method that defines them. Do not initialize these classes dynamically unless you want to handle the object lifetime manually.

Next will be a description of the cloning and releasing mechanism. It is important to know exactly when a data structure must be cloned and whether a cloned value data structure must be released, by calling the die() method, or deleted. This is critical in order to avoid memory leaks.

Cloning of data structures

Data structure clones are created when:

Example 1:

// data structure is instantiated and sent on the "Output" port
TypeRef tData("Root.Address.IPAddress");
Output.put(arrivalTime) << tData;

Exception to this rule are old methods, now obsolete:

getTypeForMember(...) // in DataStructure class;

Const references returned by some methods of data structures are references to the values inside the object.

Example 2:

// the fastest way to read a memory when no changes have occurred.
const Memory tMemory;
const ConstTypeRef tData = tMemory;

Releasing of data structures

Example 1:

go
{
  TypeRef tData = MyMemory.readData(); // clone returned
  //or
  TypeRef tData = MyMemory;
  ....
} // life time of tData ends - data structure is no longer needed and it is released.

Example 2:

TypeRef tData = MyMemory.readData(); // clone returned
....
Output.put(arrivalTime) << tData;
// data structure is placed on the output port.

Errors in using clone() and die() methods in a simulation can lead to unexpected behavior or memory leak, so try to analyze and use the data structure mechanism correctly.