Memory management

next - skip - up - start

The package does not support delayed copy. Several strategies are required to prevent unnecessary matrix copies.

Where a matrix is called as a function argument use a constant reference. For example

    YourFunction(const Matrix& A)
rather than
    YourFunction(Matrix A)

Skip the rest of this section on your first reading.


Gnu g++ (< 2.6) users please read on; if you are returning matrix values from a function, then you must use the ReturnMatrix construct.

A second place where it is desirable to avoid unnecessary copies is when a function is returning a matrix. Matrices can be returned from a function with the return command as you would expect. However these may incur one and possibly two copyings of the matrix. To avoid this use the following instructions.

Make your function of type ReturnMatrix . Then precede the return statement with a Release statement (or a ReleaseAndDelete statement if the matrix was created with new). For example

    ReturnMatrix MakeAMatrix()
    {
       Matrix A;
       ......
       A.Release(); return A;
    }
or
    ReturnMatrix MakeAMatrix()
    {
       Matrix* m = new Matrix;
       ......
       m->ReleaseAndDelete(); return *m;
    }
If your compiler objects to this code, replace the return statements with
    return A.ForReturn();
or
    return m->ForReturn();
If you are using AT&T C++ you may wish to replace return A; by return (ReturnMatrix)A; to avoid a warning message; but this will give a runtime error with Gnu. (You can't please everyone.)
Do not forget to make the function of type ReturnMatrix; otherwise you may get incomprehensible run-time errors.
You can also use .Release() or ->ReleaseAndDelete() to allow a matrix expression to recycle space. Suppose you call
    A.Release();
just before A is used just once in an expression. Then the memory used by A is either returned to the system or reused in the expression. In either case, A's memory is destroyed. This procedure can be used to improve efficiency and reduce the use of memory.

Use ->ReleaseAndDelete for matrices created by new if you want to completely delete the matrix after it is accessed.