Maya - Managing objects returned by the C++ API

All the API methods which return object pointers allocate those objects and pass ownership to your code. You are responsible for freeing them when they are no longer needed. Since they are allocated in a different module, you cannot call the delete operator on them. Instead, you must call the DeleteThis() method, which all the objects inherit from the MaxwellMayaAPIObject base class. To simplify this task, the API defines a minimalistic smart pointer template called MaxwellMayaPtr which can wrap raw pointers to API objects. Instances of the smart pointer call DeleteThis() on the wrapped object when they go out of scope. For convenience, the API also defines an instantiation of this template for every class. The name of the smart pointer instantiation is always the name of the wrapped class followed by Ptr, or ConstPtr for wrappers of const pointers. For example, the smart pointers wrapping MaxwellMayaCamera are:

typedef MaxwellMayaPtr<MaxwellMayaCamera>        MaxwellMayaCameraPtr;
typedef MaxwellMayaPtr<const MaxwellMayaCamera>  MaxwellMayaCameraConstPtr;

If you ever need to pass ownership of an API object outside a function, and the object is wrapped in a smart pointer, you can use the Detach() method of the MaxwellMayaPtr class. For example, if you want to write a function which creates and returns a mesh, you can do something like this:

MaxwellMayaMesh* MakeMesh()
{
    MaxwellMayaMeshPtr mesh(api->CreateMesh(/* arguments */));
    if(!mesh)
    {
        // MaxwellMayaPtr can wrap NULL pointers. In that case, it simply does nothing when it goes out of scope.
        return NULL;
    }
    if(!mesh->SetPositions(/* arguments */))
    {
        // You can just return and the smart pointer will correctly destroy the mesh handle.
        return NULL;
    }
    // Pass ownership of the raw pointer to the caller. Detach() sets the internal pointer to
    // NULL, so nothing happens when the smart pointer exists the scope.
    return mesh.Detach();
}

When you call the function, you can also use a smart object:

MaxwellMayaMeshPtr mesh(MakeMesh());
if(!mesh) { /* etc. */ }

The API classes are just handles to the objects in the Maxwell scene. DeleteThis() destroys only the handle, not the object represented by it. In that sense, they are similar to Maya's MFn classes. Objects which can be removed from the exported scene have a separate Destroy() method, which deletes the Maxwell object, but does not delete the handle; you still need to call DeleteThis() to free the handle object (or let a smart pointer do it). Any methods called on an API object after Destroy() was called will return an error when possible, or just do nothing (except for DeleteThis(), obviously).