New functions for memory management


Memory management is an important issue in an application such as SAMSON, where developers independently write modules, and users may use these modules in combination – and in any order. Moreover, since users may undo and redo actions, SAMSON has to ensure that any allocated memory is properly freed when it cannot be used anymore.

To help developers achieve this, the SAMSON SDK now contains new functions to manage memory. Assume for example a function adds a new structural model to the active layer when a button is pressed, in an undoable way:

// add a new structural model to the active layer
SBPointer<SBStructuralModel> structuralModel = new SBStructuralModel();
SAMSON::beginHolding("Add structural model"); // turn the undo system on
SAMSON::hold(structuralModel()); // tell SAMSON to acquire ownership of the structural model structuralModel->create(); // mark the model as created
SAMSON::getActiveLayer()->addChild(structuralModel); // add the model to the active layer
SAMSON::endHolding(); // turn the undo system off

The hold function above tells SAMSON to acquire ownership of the structural model, and makes it responsible for deletion of the structural model when it can no longer be accessed by the user (i.e. when the document is closed, or when the user undoes the action and does something else instead, thereby removing the action from the history). The hold function should be applied first, before any other undoable action.

Note that, when the hold function is applied to a data graph node, such as in the example above, SAMSON acquires ownership of the node itself and all its descendants. As a result, it is not necessary to hold the descendants individually (similarly, the create function applies to the node and its descendants).

For convenience, there are three hold functions in the SAMSON class:

static void hold(void* object); ///< Holds an object
static void hold(SBNode* node); ///< Holds a node and its descendants
static void hold(SBPointerTarget* pointerTarget); ///< Holds a pointer target allocated on the heap

and one holdArray function:

static void holdArray(void* array); ///< Holds an array allocated on the heap

Note that, in general, one should not allocate arrays of nodes or pointer targets, since they may end up being deleted individually by the user when editing the document, which is why only one holdArray function is available.


Leave a Reply

Your email address will not be published.

  • Subscribe

    Subscribe to make sure you receive all our updates, tips and tutorials