you pretty much HAVE to allocate a new space into which to copy over the cells of the matrix, otherwise when the original matrix object is destroyed, the new one will crash, since the memory for the matrix cells would be freed.
Copy Constructor/Memory Allocation
Get off my lawn!
it SHOULD be CMatrix (or whatever your matrix class is called) rather than CMatrix& or CMatrix*.
then you return the temp matrix on the stack (which is more overhead, but cant be helped)
however, if for some reason this doesnt work, you may have to just overload the += and *= operators.
Get off my lawn!
Now I started to test the class and, when I only compile the class (source and header, with implementation and declaration respectively), it is fine, no errors are found.
But when I add a void main() at the end of the file and put the line Matrix
Please guys, help me out again...
blah = new T[_pNRows*_pnCols]
And then access it like this
blah[_pnCols*row + col]
But now I'm starting to overload the operators like +, * to implement all the ops with matrices. When I use a statement like A = B + C (all these variables are matrices), the values from B and C are summed and put on a new temp matrix which is returned from the overloaded operator function. And it happens that the default copy constructor copies the POINTER _pMatrix, making two different and independent pointers point to the same resource. Now, after the temp matrix with the summed values is returned, it runs out of scope and its destructor (which deallocates the resource) is called. And then the A matrix contains a _pMatrix member pointing to a deleted resource!!!
All I could think of was to implement a new copy constructor that would copy all non-pointer members of the source class to the destination class, allocate memory for the destination class' _pMatrix member and copy the entire contents from the source _pMatrix. Then, I have two different pointers pointing to two different resources, but both resources are identical.
If I'm using a 4x4 matrix of double, imagine the memory it was going to use!!!! It would take a lot of resources from the heap and cycles from the processor to do all this!!!!
Isn't there any other viable solution to copy the source object and its allocated resource to the destination???
CMatrix *CMatrixArray::get(int x, int y)
{
return(&m_array[(y*m_dimx)+x])
}
or something. Not sure if it'd make sense in your situation, just thought I'd mention it as a wild thought.
Mason McCuskey
Spin Studios
http://www.spin-studios.com
The Cuttlefish Engine lets anyone develop great games for iPad, iPhone, Android, WP7, the web, and more!