Path: utzoo!attcan!uunet!mcsun!inria!timpit0!cnetlu!ranson From: ranson@cnetlu.UUCP (Ranson) Newsgroups: comp.lang.c++ Subject: Defining operators Message-ID: <1253@cnetlu.UUCP> Date: 20 Nov 89 13:19:52 GMT Reply-To: ranson@cnetlu.UUCP (Ranson) Organization: C.N.E.T. Lannion 22301 LANNION FRANCE Lines: 36 When defining operators on objects of a class in C++ (e.g. + on matrices), there are currently two possibilities (leaving aside the equivalent using member functions, and assuming args passed by reference): matrix& operator+(matrix& x, matrix& y) { ... } matrix operator+(matrix& x, matrix& y) { ... } The first one looks promising, but since returning a reference to a local variable is an error, one has to allocate a new matrix for the result, and disposing of it afterwards may not be easy, especially in complex expressions (e.g. how does one dispose of the result of A+B in (A+B)+C ?). Stroustrup recommends using the second form, where intermediate results will be dealt with automatically by C++, but this also means that the result needs to be copied for each operation. As I understand it, an expression like: X = (A+B)+C; is translated into: matrix U; U = operator+(A,B); X = operator+(U,C); Why not allow a third form, where the caller would pass as a third argument a reference to the place where the result should be put? void operator+(matrix& x, matrix& y, matrix& result) { ... } The previous example would translate into: matrix U; operator+(A,B,U); operator+(U,C,X); and no copying would be necessary. Am I missing something obvious? Daniel Ranson X400: ranson@lannion.cnet.fr uucp: ranson@cnetlu.fr, or ...!mcvax!inria!cnetlu!ranson