Path: utzoo!utgpu!watmath!iuvax!mailrus!uunet!microsoft!jimad From: jimad@microsoft.UUCP (Jim Adcock) Newsgroups: comp.lang.c++ Subject: Re: Defining operators Message-ID: <9182@microsoft.UUCP> Date: 27 Nov 89 20:29:02 GMT References: <1253@cnetlu.UUCP> Reply-To: jimad@microsoft.UUCP (Jim Adcock) Organization: Microsoft Corp., Redmond WA Lines: 58 In article <1253@cnetlu.UUCP> ranson@cnetlu.UUCP (Ranson) writes: ... >matrix operator+(matrix& x, matrix& y) { ... } >Stroustrup recommends using 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? The C++ compilers I am familiar with do not necessarily work as you assume. If I declare as follows: matrix(const matrix&); void friend operator=(matrix&, const matrix&); matrix friend operator+(const matrix& a, const matrix& b); ...then my 1.2 compatible compiler does what you want -- I can write: matrix D = A + B + C; and no matrix copying will be done. BUT NOTE: This is not the same as if you write: D = A + B + C; where D was declared previously. When one writes "matrix D =" one is telling the compiler to *construct* a new matrix out of the results of "A + B + C". Whereas when one writes "D = " you tell the compiler you want to have D *assigned* the value of some matrix -- but what matrix? -- one constructed from "A + B + C" ---- sooo you force the compiler to introduce a temporary that then can be copied into D: D = A + B + C; means: D = (matrix Tmp(A + B + C)); In C++ construction vs assignment are very much *not* the same thing. Unfortunately, a plethora of syntaxes (syntacti?) for construction vs assignment confuses the issue. Even if one does not optimally use construction verses assignment, C++ compilers can avoid most of the unnecessary copying by creating op+ in the three parameter form as you suggest.