Creating and Destroying Plug-in Instances

The 3ds Max API provides a method used to allocate memory when a new instance of a plug-in class is required. It also provides several different ways to deallocate this memory depending on the plug-in type. In the most common case, these methods are ClassDesc::Create() and Animatable::DeleteThis().

Note: While the Create() method is a member of ClassDesc, developers should use ClassDesc2 which inherits from ClassDesc.

When 3ds Max needs to create a new instance of a plug-in class, it calls the Create() method of the class descriptor. This method returns a new instance of the plug-in class. The memory for the class may be allocated by using the new operator as shown below:

void* Create(BOOL loading = FALSE) { return new MyObject; }

For example, when 3ds Max loads a file from disk it needs to create instances of the plug-ins that are used (the geometric objects, lights, cameras, materials, controllers, etc.). It does this by calling ClassDesc::Create().

The memory must be freed when 3ds Max is done with the item. Usually a method named DeleteThis() is called. This method is called to free the memory associated with the plug-in class. Since the memory was allocated with the new operator, it must be de-allocated using the delete operator as shown below:

void Plugin::DeleteThis() { deletethis; }
Note: Plug-in's should not put their DeleteThis methods inline. First the DeleteThis method is virtual, and so conflicts with the whole idea of inline methods. Second, when put inline, this method can cause incorrect destruction of objects and memory leaks.

For plug-ins that are part of the Animatable class hierarchy, DeleteThis() is a method of Animatable. For plug-ins that are not derived from Animatable there may be a non-inherited DeleteThis() method. For example, the UtilityObj class used to create Utility plug-ins is not derived from Animatable and has its own DeleteThis().

The DeleteThis() method also gives the developer control over deleting. For example, a Utility plug-in object may be statically declared and not actually declared in the heap. A utility plug-in such as \MAXSDK\SAMPLES\RETIRED\ASCIIOUT.CPP would implement DeleteThis() to do nothing since there is no heap memory to free. For example:

void DeleteThis() {}

A few plug-in types have no DeleteThis() method at all -- 3ds Max deletes the memory directly. The Image Filter and Compositor plug-in types are derived from ImageFilter. They are allocated by system using ClassDesc::Create() but have no DeleteThis() method to override. The system just calls the operatordelete() operator on the object instance.