Newsgroups: comp.lang.c++ Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!think.com!mintaka!bloom-picayune.mit.edu!athena.mit.edu!bjaspan From: bjaspan@athena.mit.edu (Barr3y Jaspan) Subject: Efficient return of objects from overloaded operators Message-ID: <1991Apr16.193118.15066@athena.mit.edu> Sender: news@athena.mit.edu (News system) Organization: Massachusetts Institute of Technology Date: Tue, 16 Apr 91 19:31:18 GMT Lines: 30 In my Matrix class, I have several overloaded operators of the form Matrix operator*(const Matrix&, const Matrix&); The function does the obvious thing: allocates a local Matrix on the stack, multiplies into it, and returns it. This, of course, is very inefficent because I have to copy the Matrix object out of the stack frame at the end. Is there a good solution for this problem? Unacceptable solutions I've thought of: (1) Have a static Matrix local to the function. No good because it will fail in the multithreaded environment. (2) Allocate a matrix on the heap and return a reference to it. No good because then the matrix is never freed (since there is no garbage collection). The only possibly good solution I've thought of (I haven't worked through it to make sure it's a good idea) is allocate a matrix on the heap and return a smart reference that will deallocate the object when it is no longer used. In fact, I have a copy-on-write template that would be ideal for this, since it would provide COW semantics in addition to avoiding the copy of the stack object. But that would mean I'd have to implement an entire set of operators like COW& operator*(const COW&, const COW&) etc., and this seems kind of tedious. (It also means the Matrix class would depend on a specific smart reference class, which doesn't seem like a good idea.) Suggestions? -- Barr3y Jaspan, bjaspan@mit.edu