In C++, it is common to construct a variable from an existing variable. For example, this occurs when returning a variable from a function, when passing a variable by value, or when creating a temporary in arithmetic expressions. This construction is accomplished by a special constructor called the copy constructor. When a Rogue Wave matrix is constructed by the copy constructor, the copy constructor causes the data in the new object to reference the data in the old object. This is done for efficiency, since it takes much longer to copy the data than to reference it. If you have used the Math.h++ vector classes, you are familiar with this technique because the vector, matrix, and array classes all use it. The simplest way to illustrate this kind of referencing is with an example:
#include <rw/dskewmat.h> // 1 #include <iostream.h> main() { DoubleSkewMat S(3,3); // 2 S.zero(); DoubleSkewMat R = S; // 3 DoubleSkewMat T = S.copy(); // 4 R(1,2) = 5; // 5 T(2,1) = 3; // 6 cout << "R= " << R << endl; // 7 cout << "S= " << S << endl; cout << "T= " << T << endl; }
//1 | The first line includes the header file for the DoubleSkewMat matrix type. This type represents a square skew symmetric matrix of double precision numbers. In a skew symmetric matrix, an off-diagonal entry Aij is equal to the negative of entry Aji. You can see that only half of a skew symmetric matrix needs to be stored and, indeed, this is how the DoubleSkewMat class is implemented. |
//2 | In this line, S is defined to be a 3 x 3 skew symmetric matrix of doubles. The following line sets each element of the matrix to 0. |
//3 | R is defined to be the same as S. This syntax invokes the DoubleSkewMat copy constructor to build R. Constructing R in this way causes it to reference the same data as S. |
//4 | In //3 the copy constructor caused R to reference the same data as S. How can you create a matrix from S which does not have this aliased property? Make a copy using the copy() function. In //4, T is created from a copy of S. Hence, the data in T is completely independent from S. |
//5 | This line sets element (1,2) of R equal to 5. There are two interesting ramifications. First, because R is a skew symmetric matrix, changing element (1,2) automatically changes element (2,1). Second, the matrix S also changes because both S and R reference the same data. |
//6 | This line sets element (2,1) of T equal to 3. This change does not affect any of the other matrices since T is an independent copy. Because T is a skew symmetric matrix, changing element (2,1) must also change element (1,2), just as in //5. |
//7 | Print the matrices. Notice that R and S are the same, because they reference the same data. |
For additional information on the technique described in this example, please see the Math.h++ User's Guide chapter on vectors, matrices, and arrays.
>©Copyright 1999, Rogue Wave Software, Inc.
Contact Rogue Wave about documentation or support issues.