Newsgroups: comp.lang.c++
Path: utzoo!utgpu!news-server.csri.toronto.edu!torsqnt!hybrid!scifi!watson!blinn.watson.ibm.com!mittle
From: mittle@blinn.watson.ibm.com (Josh Mittleman)
Subject: Re: Efficient return of objects from overloaded operators
Sender: @watson.ibm.com
Message-ID: <1991Apr18.172934.22246@watson.ibm.com>
Date: Thu, 18 Apr 91 17:29:34 GMT
References:  <1991Apr16.193118.15066@athena.mit.edu>
Organization: IBM T. J. Watson Research

One approach is to have your Matrix class contain a pointer to an
auxilliary object MatrixData, which actually contains the matrix data.
This object is normally allocated, initialized, and/or copied in the
constructors and operator=, and deallocated in ~Matrix().  You need one
extra constructor, Matrix::Matrix(int cols, int rows, MatrixData&), which
should be private.

Then, to write a function which returns Matrix, by value, you allocate a
MatrixData on the heap, initialize its value within the function, and then
return a reference to it.

This avoids the need to copy the data.  Of course, it does introduce a
small amount of overhead in pointer chasing.

===========================================================================
Josh Mittleman (mittle@watson.ibm.com or joshua@paul.rutgers.edu)
J2-C28 T.J. Watson Research Center, PO Box 704, Yorktown Heights, NY  10598
